# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-duplicate-tool-effect-replay-when-an-mcp-http-native-session-resumes-after-a-severed-sse-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-duplicate-tool-effect-replay-when-an-mcp-http-native-session-resumes-after-a-severed-sse-stream.warrant.json
# Markdown SHA-256:   4a3f272f863dca3793d2b3ecae7559ad609c37f385dd42f230fa2b04ef89435e
# Code AST SHA-256:   5320528c739aa44859da3a5941a12c788c761522c7a75d1aa024393eba60f8a2
# Verified Classes:   UnsafeResumeError, ResumeOutcome
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnsafeResumeError(RuntimeError):
    """Raised when a client attempts to re-issue a tool call on a resume
    path where the prior outcome is unknown. Re-issuing here risks
    duplicate side effects for non-idempotent tools."""


class ResumeOutcome:
    REPLAYED = "replayed"
    IN_FLIGHT = "in_flight"
    UNKNOWN_EVENT = "unknown_event_id"
    SESSION_EXPIRED = "session_expired"
    DUPLICATE = "duplicate"


def classify_resume(status_code: int, session_valid: bool) -> str:
    if status_code == 200:
        return ResumeOutcome.REPLAYED
    if status_code == 409:
        return ResumeOutcome.DUPLICATE
    if status_code == 400 and session_valid:
        return ResumeOutcome.UNKNOWN_EVENT
    if status_code == 404 or not session_valid:
        return ResumeOutcome.SESSION_EXPIRED
    raise UnsafeResumeError(f"unclassified resume status {status_code}")


def on_resume(outcome: str, request_id: str, tool_is_idempotent: bool) -> str:
    """Decide the next action. Returns an action token for the orchestrator."""
    if outcome == ResumeOutcome.REPLAYED:
        return "consume_events"
    if outcome == ResumeOutcome.IN_FLIGHT:
        return "wait"
    if outcome == ResumeOutcome.DUPLICATE:
        return "fetch_existing_result"
    if outcome == ResumeOutcome.SESSION_EXPIRED:
        # Session is gone; request may or may not have run. Only safe to
        # re-issue if the tool is idempotent OR the server has no record
        # but the caller accepts possible duplication.
        if tool_is_idempotent:
            return "reissue_same_request_id"
        return "reestablish_then_status_probe"
    if outcome == ResumeOutcome.UNKNOWN_EVENT:
        # Stream buffer evicted but session alive: outcome is ambiguous.
        # Blindly re-issuing here is the exact duplicate-effect trigger.
        if tool_is_idempotent:
            return "reissue_same_request_id"
        raise UnsafeResumeError(
            f"request {request_id} has unknown outcome after stream eviction; "
            f"non-idempotent tool must not be re-issued without a status probe"
        )
    raise UnsafeResumeError(f"unhandled resume outcome {outcome!r}")
