# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-resumable-stream-last-event-id-replay-as-non-idempotent-and-re-validate-tool-side-effects-before-resuming.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-resumable-stream-last-event-id-replay-as-non-idempotent-and-re-validate-tool-side-effects-before-resuming.warrant.json
# Markdown SHA-256:   4378a6762b1f8721355a01da0086eff8c72555eaab0cd408ea27513be1a287bd
# Code AST SHA-256:   4b84f26b03292e36c43cf180cf08342e8cb7c923fdce66237b99fcc64b5d0798
# Verified Classes:   ReplayLedgerMismatch, DispatchLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ReplayLedgerMismatch(RuntimeError):
    """Raised when a replayed SSE event references a call_id the client
    never durably dispatched, making semantic replay unsafe."""
    pass


class DispatchLedger:
    def __init__(self, durable_store):
        self._store = durable_store  # survives reconnect / process restart

    def record_dispatch(self, call_id: str, tool: str, args_digest: str) -> None:
        # MUST be written before the tool call is sent on the wire.
        self._store.put(call_id, {"tool": tool, "args": args_digest, "state": "dispatched"})

    def record_result(self, call_id: str, status: str) -> None:
        entry = self._store.get(call_id)
        if entry is None:
            raise ReplayLedgerMismatch(
                f"result for undispatched call_id={call_id}; replay is non-idempotent"
            )
        entry["state"] = status
        self._store.put(call_id, entry)

    def known(self, call_id: str) -> bool:
        return self._store.get(call_id) is not None


def handle_reconnect_event(event, ledger: DispatchLedger, server_status_lookup):
    call_id = event.get("call_id")

    if event["type"] == "tool_call_result":
        if not ledger.known(call_id):
            # Do NOT retry the turn. Reconcile against authoritative state.
            status = server_status_lookup(call_id)
            if status is None:
                raise ReplayLedgerMismatch(
                    f"replayed result for unknown call_id={call_id} and server "
                    f"cannot confirm terminal state; re-validation required "
                    f"before any re-execution"
                )
            ledger.record_dispatch(call_id, event["tool"], event.get("args_digest", ""))
            ledger.record_result(call_id, status)
            return {"action": "reconciled", "call_id": call_id}
        ledger.record_result(call_id, event["status"])
        return {"action": "accepted", "call_id": call_id}

    if event["type"] == "tool_call_start":
        if ledger.known(call_id):
            # Duplicate start from replay; suppress re-dispatch.
            return {"action": "suppressed", "call_id": call_id}
        ledger.record_dispatch(call_id, event["tool"], event.get("args_digest", ""))
        return {"action": "dispatched", "call_id": call_id}

    return {"action": "ignored", "type": event["type"]}
