# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-stream-resumption-last-event-id-mismatch-as-a-hard-session-identity-violation-rather-than-a-benign.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-stream-resumption-last-event-id-mismatch-as-a-hard-session-identity-violation-rather-than-a-benign.warrant.json
# Markdown SHA-256:   f53da28218cb994296e2ae404da99a33341ccaa8b6f24006e1464267a294d900
# Code AST SHA-256:   ad23059892f705ce56af84c791088ed1ffad6711cec788f25d16f49a641bd33f
# Verified Classes:   SessionIdentityViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SessionIdentityViolation(RuntimeError):
    """Raised when a resume attempt cannot be attributed to the current session incarnation."""
    pass


def resume_stream(session, presented_last_event_id, server_events):
    """
    session: object with .incarnation_token and .event_log {event_id: payload}
    presented_last_event_id: string like 'sess_<uuid>:<seq>' or bare '<seq>'
    server_events: list of (event_id, payload) currently known to the server
    """
    # 1. Structural attribution: the ID must carry the current incarnation token.
    if ":" not in presented_last_event_id:
        # Bare integer IDs cannot prove session identity. Refuse numeric fallback.
        raise SessionIdentityViolation(
            f"Last-Event-ID {presented_last_event_id!r} lacks incarnation namespace; "
            f"cannot attribute to session {session.incarnation_token}"
        )

    token, _, seq = presented_last_event_id.partition(":")
    if token != session.incarnation_token:
        raise SessionIdentityViolation(
            f"Last-Event-ID belongs to incarnation {token!r}, "
            f"current session is {session.incarnation_token!r}; refusing cross-session replay"
        )

    # 2. Same incarnation: the ID must still be present in the retained log.
    if presented_last_event_id not in session.event_log:
        # In-incarnation but evicted: gap too old to replay. Reject, do NOT silently skip.
        raise SessionIdentityViolation(
            f"Event {presented_last_event_id!r} evicted from log; "
            f"silent gap would corrupt agent observation stream"
        )

    # 3. Safe to resume: replay strictly after the last-seen event.
    last_seq = int(seq)
    return [
        (eid, payload)
        for eid, payload in server_events
        if eid.startswith(f"{session.incarnation_token}:")
        and int(eid.rsplit(":", 1)[1]) > last_seq
    ]
