# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-resume-an-mcp-streamable-http-session-when-the-sse-to-http-upgrade-negotiates-a-different-last-event-id-l.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-resume-an-mcp-streamable-http-session-when-the-sse-to-http-upgrade-negotiates-a-different-last-event-id-l.warrant.json
# Markdown SHA-256:   ab562548ab701d15666d3cac2ffbea02fa4bc1b4e94ea16f068b2d9175e64d8c
# Code AST SHA-256:   5f431b9fd9f8ab9123343b04aee3e44899319b07a0fc76ff3b965a90664dd010
# Verified Classes:   LineageMismatchError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class LineageMismatchError(RuntimeError):
    """Raised when a resumption request's Last-Event-ID lineage does not match
    the session's current event lineage, or when a contiguous replay cannot be
    proven. Must never be downgraded to 'resume from oldest'."""
    pass


def resolve_resumption(session, presented_last_event_id: str):
    # session: object with .session_id, .current_lineage, .buffer (dict keyed by (lineage, event_id)),
    #          .snapshot_lineage (or None), .head_event_id
    lineage, _, event_id = presented_last_event_id.rpartition(":evt-")
    if not lineage or not event_id.isdigit():
        raise LineageMismatchError(f"malformed Last-Event-ID {presented_last_event_id!r}")

    if lineage != session.current_lineage:
        # Different generation: the numeric suffix is meaningless. Only a snapshot
        # that predates the presented lineage may be used, and it must be signalled.
        if session.snapshot_lineage is not None and session.snapshot_lineage <= lineage:
            return {"mode": "snapshot", "from": session.snapshot_lineage}
        raise LineageMismatchError(
            f"lineage {lineage!r} != session lineage {session.current_lineage!r}; "
            f"no snapshot precedes it -- refusing delta resumption"
        )

    key = (lineage, int(event_id))
    if key not in session.buffer:
        # Same lineage but gap: the contiguous history was truncated out from under the client.
        # This is a lineage break for resumption purposes, not a 'resume from oldest' case.
        raise LineageMismatchError(
            f"event {presented_last_event_id!r} not retained in buffer; "
            f"head={session.head_event_id} -- gap, refusing silent replay"
        )

    # Contiguity check: successor chain must reach head with no gap.
    cursor = int(event_id) + 1
    while cursor <= session.head_event_id:
        if (lineage, cursor) not in session.buffer:
            raise LineageMismatchError(
                f"gap at {lineage}:evt-{cursor:06d} between presented ID and head"
            )
        cursor += 1
    return {"mode": "contiguous", "from": (lineage, int(event_id) + 1)}


def handle_resumption_get(session, headers):
    presented = headers.get("Last-Event-ID")
    if presented is None:
        # No checkpoint: fresh stream, no resumption contract to honor.
        return {"mode": "fresh"}
    plan = resolve_resumption(session, presented)  # raises LineageMismatchError on break
    if plan["mode"] == "snapshot":
        # Emit an explicit resync marker so the client knows it is NOT receiving a delta.
        return {"status": "resync", "snapshot_from": plan["from"]}
    return {"status": "resume", "from": plan["from"]}
