# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sse-event-id-reuse-from-silently-replaying-a-poisoned-tool-call-result-across-an-mcp-streamable-session-resume.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sse-event-id-reuse-from-silently-replaying-a-poisoned-tool-call-result-across-an-mcp-streamable-session-resume.warrant.json
# Markdown SHA-256:   5e1acaf8d836f435925ab3129d7f46a9da331dfdb0effb071e7be2277f60db14
# Code AST SHA-256:   7b0354b82f7afb2d188c920016dafe219b9007a6cfbe296c5001224e8cbaed42
# Verified Classes:   ResumeReplayPoisoningError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ResumeReplayPoisoningError(RuntimeError):
    """Raised when a replayed SSE event cannot be safely attributed to the
    outstanding tool call during an MCP streamable-session resume."""
    pass


def commit_replayed_result(
    event: dict,
    outstanding_invocation_id: str,
    last_consumed_event_id: int,
) -> dict:
    evt_id = event.get("event_id")
    evt_invocation = event.get("invocation_id")
    evt_type = event.get("type")

    if evt_type != "result":
        raise ResumeReplayPoisoningError(
            f"non-result event {evt_type!r} routed to result commit path"
        )

    # Invariant 1: event-ID must strictly advance past the durable cursor.
    if evt_id is None or evt_id <= last_consumed_event_id:
        raise ResumeReplayPoisoningError(
            f"event_id {evt_id!r} does not advance past cursor "
            f"{last_consumed_event_id}; replay space likely rewound"
        )

    # Invariant 2: the result must belong to the request we are waiting on.
    if evt_invocation != outstanding_invocation_id:
        raise ResumeReplayPoisoningError(
            f"replayed result invocation_id {evt_invocation!r} != "
            f"outstanding {outstanding_invocation_id!r}; "
            f"possible concurrent-retry collision"
        )

    return event
