# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-streamable-http-resumption-from-replaying-a-server-initiated-push-into-a-post-resume-sampling-turn.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-streamable-http-resumption-from-replaying-a-server-initiated-push-into-a-post-resume-sampling-turn.warrant.json
# Markdown SHA-256:   f16f6a756665cf9a5f30d8591d6358025d2194400b6c7f3529bd51bb11d39f88
# Code AST SHA-256:   725a1e0a04fe935e7f0c964afdba99cd7570bc9c1a3366e6fc64b5836b198611
# Verified Classes:   ResumptionCausalityError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ResumptionCausalityError(RuntimeError):
    """Raised when a replayed server-initiated request cannot be safely
    re-attached or dropped because its causal predecessor is unknown."""


def resume_stream(
    last_event_id: str,
    seen_request_ids: set[str],
    server_oldest_live_pending_id: str | None,
    replay_buffer: list[dict],
) -> list[dict]:
    """Filter a replayed event buffer down to events safe to execute.

    Invariant: a replayed sampling/elicitation request is executed only if
    its id is unseen AND the cursor is within the server's live pending
    horizon. Otherwise it is dropped (seen) or the session fails closed
    (unknown predecessor).
    """
    if server_oldest_live_pending_id is None:
        # Server has no live pending requests: any replay is stale.
        return [e for e in replay_buffer if e.get("method") not in
                ("sampling/createMessage", "elicitation/create")]

    if last_event_id < server_oldest_live_pending_id:
        raise ResumptionCausalityError(
            f"Last-Event-ID {last_event_id!r} predates oldest live pending "
            f"request {server_oldest_live_pending_id!r}; replay would "
            f"re-execute requests with unknown causal predecessors. "
            f"Fail session closed."
        )

    safe: list[dict] = []
    for evt in replay_buffer:
        method = evt.get("method")
        if method in ("sampling/createMessage", "elicitation/create"):
            req_id = evt.get("id")
            if req_id in seen_request_ids:
                continue  # drop: already answered or in flight
        safe.append(evt)
    return safe
