# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-resumable-sse-stream-has-silently-forked-its-session-lineage.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-resumable-sse-stream-has-silently-forked-its-session-lineage.warrant.json
# Markdown SHA-256:   790ed10242d276ac9dba539a13fe20797583a7c432430e6b91e03ee4b359f24a
# Code AST SHA-256:   16b22159f0659ab30b8533858391852210a2e57a05c49fa431ba19f809b6f423
# Verified Classes:   SessionLineageForkError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SessionLineageForkError(RuntimeError):
    """Raised when a resumption token's generation exceeds the client's acknowledged generation."""
    pass


def resume_stream(client, session_id: str, last_event_id: int, resumption_token: dict) -> dict:
    """
    Attempt to resume an MCP SSE stream. Returns a reconciliation verdict.
    Raises SessionLineageForkError if the server has forked the lineage and
    the client must reconcile before dispatching any gated side effects.
    """
    acked_generation = client.acknowledged_generation(session_id)
    token_generation = resumption_token.get("generation", 0)

    # Safe-retry regime: token generation matches what we last acknowledged.
    if token_generation == acked_generation:
        return client.replay_from(session_id, last_event_id)

    # Generation bump we never acknowledged => ambiguous lineage.
    if token_generation > acked_generation:
        # Do NOT dispatch gated work. Reconcile first.
        verdict = client.request_reconcile(
            session_id=session_id,
            acknowledged_cursor=last_event_id,
            acknowledged_generation=acked_generation,
            presented_generation=token_generation,
        )
        if verdict.get("status") != "pure_replay":
            raise SessionLineageForkError(
                f"session {session_id} forked: acknowledged gen {acked_generation}, "
                f"server presented gen {token_generation}, "
                f"divergent events: {verdict.get('divergent_event_ids')}"
            )
        client.commit_generation(session_id, token_generation)
        return client.replay_from(session_id, last_event_id)

    # Server presented an older generation than we acknowledged: token reuse / rollback.
    raise SessionLineageForkError(
        f"session {session_id} token rollback: acknowledged gen {acked_generation}, "
        f"server presented gen {token_generation}"
    )
