# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-mcp-streamable-session-resumption-against-sse-to-stateless-fallback-without-re-admitting-replayed-tool-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-mcp-streamable-session-resumption-against-sse-to-stateless-fallback-without-re-admitting-replayed-tool-effects.warrant.json
# Markdown SHA-256:   81861d3b43316e30550235b62b73d365b5c17be4a44cc506b7a6cb4ea4f903f3
# Code AST SHA-256:   a7ecd293ddbc58fd2190aeabdafc18b5dce1e553b8d20490eea3959973aa3c65
# Verified Classes:   IndeterminateEffectError, Observation, InFlightRequest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class IndeterminateEffectError(RuntimeError):
    """Raised when a request's side effects cannot be determined after a
    streamable-session -> stateless fallback, and neither re-execution nor
    reconciliation is safe."""

    def __init__(self, request_id: int, tool: str, target: str, last_event_id: Optional[str]):
        self.request_id = request_id
        self.tool = tool
        self.target = target
        self.last_event_id = last_event_id
        super().__init__(
            f"indeterminate effect: request {request_id} ({tool} -> {target}) "
            f"after session loss; last_event_id={last_event_id}"
        )


class Observation(Enum):
    NONE = "none"            # no events observed; effect could not have committed
    PROGRESS_ONLY = "progress"  # progress seen, no result; commit status unknown
    RESULT = "result"        # terminal result observed; effect known


@dataclass
class InFlightRequest:
    request_id: int
    tool: str
    target: str
    observation: Observation
    idempotent: bool
    reconcilable: bool
    last_event_id: Optional[str] = None


def resolve_on_session_loss(req: InFlightRequest) -> str:
    """
    Decide what to do when the server returns 404 for the session while
    `req` is in flight. Returns an action string, or raises
    IndeterminateEffectError when the effect cannot be resolved safely.
    """
    if req.observation is Observation.RESULT:
        # Effect known and already observed; do not re-execute.
        return "complete"

    if req.observation is Observation.NONE:
        # No event observed; no effect could have committed. Safe to retry.
        return "re-execute-stateless"

    # observation is PROGRESS_ONLY: the dangerous branch.
    if req.idempotent:
        return "re-execute-stateless"

    if req.reconcilable:
        return "reconcile-then-decide"

    # Non-idempotent, non-reconcilable, partial observation.
    raise IndeterminateEffectError(
        request_id=req.request_id,
        tool=req.tool,
        target=req.target,
        last_event_id=req.last_event_id,
    )


def handle_session_404(in_flight: list[InFlightRequest]) -> dict[int, str]:
    """Apply the decision boundary to every in-flight request; surface
    indeterminate ones as errors rather than silently resolving them."""
    actions: dict[int, str] = {}
    errors: list[IndeterminateEffectError] = []
    for req in in_flight:
        try:
            actions[req.request_id] = resolve_on_session_loss(req)
        except IndeterminateEffectError as exc:
            errors.append(exc)
    if errors:
        # Propagate upward with full context; do not retry blindly.
        raise IndeterminateEffectError(
            request_id=errors[0].request_id,
            tool=errors[0].tool,
            target=errors[0].target,
            last_event_id=errors[0].last_event_id,
        )
    return actions
