# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-tool-call-replay-corruption-when-a-partial-network-partition-splits-the-sse-stream-from-the-json-rpc-response-channel.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-tool-call-replay-corruption-when-a-partial-network-partition-splits-the-sse-stream-from-the-json-rpc-response-channel.warrant.json
# Markdown SHA-256:   12c1e7cadc69e122d70d667bde3b5efba0bfd5131cc7157d008f7227b9f75b39
# Code AST SHA-256:   8a139a32f359dbc2f371841de11a686758681f60ae2241484e9c69998d0bef9b
# Verified Classes:   ReplayInvariantViolation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ReplayInvariantViolation(RuntimeError):
    """Raised when a committed tool-call id resolves more than once,
    or when a reconnected stream delivers a result for an abandoned id."""


def apply_stream_event(ledger: dict, event: dict) -> None:
    """Apply one SSE-delivered JSON-RPC result against the request ledger.

    ledger: {id: {"state": "sent"|"acked"|"resolved"|"abandoned", ...}}
    event:  {"id": int, "result": ..., "last_event_id": int}
    """
    rid = event["id"]
    entry = ledger.get(rid)

    if entry is None:
        raise ReplayInvariantViolation(
            f"result for unknown id {rid}: server replayed an id the client "
            f"never committed (possible cross-session replay)"
        )

    if entry["state"] == "abandoned":
        # A late result for a request we tombstoned must be dropped, never surfaced.
        raise ReplayInvariantViolation(
            f"result for abandoned id {rid}: retry supervisor abandoned this "
            f"request but the server still delivered it; surfacing it would "
            f"inject a stale fact into the context window"
        )

    if entry["state"] == "resolved":
        # The core failure: same committed id delivered twice after reconnect.
        raise ReplayInvariantViolation(
            f"duplicate resolution for committed id {rid}: already resolved at "
            f"last_event_id={entry.get('resolved_at')}, now replayed at "
            f"last_event_id={event['last_event_id']}; agent has already reasoned "
            f"on the first result and will treat this as a state change"
        )

    if entry["state"] not in ("acked", "sent"):
        raise ReplayInvariantViolation(
            f"illegal state transition for id {rid}: {entry['state']} -> resolved"
        )

    entry["state"] = "resolved"
    entry["resolved_at"] = event["last_event_id"]
    entry["result"] = event["result"]


def on_stream_failure(ledger: dict, supervisor_wants_retry_of: int) -> None:
    """Guard the retry supervisor: a committed request may never be re-issued."""
    entry = ledger.get(supervisor_wants_retry_of)
    if entry and entry["state"] in ("acked", "resolved"):
        raise ReplayInvariantViolation(
            f"supervisor attempted to re-issue committed id "
            f"{supervisor_wants_retry_of} (state={entry['state']}); recovery "
            f"must be a stream replay against the ledger, not a new tools/call"
        )
