# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-mcp-streamable-session-is-actually-resuming-the-same-logical-turn-versus-silently-replaying-a-divergent-o.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-mcp-streamable-session-is-actually-resuming-the-same-logical-turn-versus-silently-replaying-a-divergent-o.warrant.json
# Markdown SHA-256:   d6dc0397369180b3337b0acce615b066f510a4375303a32e75777042e4899b38
# Code AST SHA-256:   082744a40546aa60fe0708e5944de2827c388b45f191fe841922c55225ad2fd9
# Verified Classes:   ResumptionDivergenceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ResumptionDivergenceError(RuntimeError):
    """Raised when a resumed MCP streamable-session continues a different
    logical turn than the one the client believes it is resuming."""
    pass


def verify_resume_continuity(
    expected_turn_nonce: str,
    expected_open_invocations: set[str],
    first_event: dict,
) -> None:
    """
    Called on the FIRST event received after a Last-Event-ID resume.
    Fails closed if the event does not co-refer to the turn being resumed.

    first_event is expected to carry:
      - "turnNonce": server-issued nonce bound at turn start
      - "invocationId": present on progress/result events for tool calls
    """
    actual_nonce = first_event.get("turnNonce")
    if actual_nonce != expected_turn_nonce:
        raise ResumptionDivergenceError(
            f"resumed stream carries turn nonce {actual_nonce!r}, "
            f"expected {expected_turn_nonce!r}; cursor is valid but "
            f"turn-divergent — abandon resume, re-issue as new turn"
        )

    inv = first_event.get("invocationId")
    if inv is not None and inv not in expected_open_invocations:
        raise ResumptionDivergenceError(
            f"resumed stream references invocation {inv!r} not in open set "
            f"{sorted(expected_open_invocations)!r}; server likely retried "
            f"the turn internally and re-numbered the log — refuse to splice"
        )


def resume_or_reissue(
    client,
    session_id: str,
    last_event_id: str,
    expected_turn_nonce: str,
    open_invocations: set[str],
    original_request: dict,
):
    stream = client.resume(session_id, last_event_id)
    first = next(stream)
    try:
        verify_resume_continuity(expected_turn_nonce, open_invocations, first)
    except ResumptionDivergenceError:
        # Fail closed: discard in-flight turn state, start a clean turn.
        client.discard_turn_state(session_id, expected_turn_nonce)
        return client.issue_new_turn(original_request)
    return client.continue_with(stream, first)
