# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-durability-when-an-mcp-streamable-http-session-resumes-across-a-backpressure-stall.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-durability-when-an-mcp-streamable-http-session-resumes-across-a-backpressure-stall.warrant.json
# Markdown SHA-256:   fa03b1d2550953c4e813c503071ddd194e26c6166704b8d7d15c976e30b2845f
# Code AST SHA-256:   820d099c6b19697e8e8339b6a04d3c1b005231f4f14dd25d8db0662cfd9d4220
# Verified Classes:   StreamResumptionViolation, EventStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StreamResumptionViolation(RuntimeError):
    """Raised when an event store would evict an unacknowledged side-effecting event,
    or when a replay request asks for an event below the retained floor."""


class EventStore:
    def __init__(self, capacity: int, session_ttl_s: float):
        self.events: dict[int, dict] = {}
        self.acked_floor: int = 0          # client's last acknowledged id
        self.committed_side_effects: set[int] = set()
        self.capacity = capacity
        self.session_ttl_s = session_ttl_s

    def record(self, event_id: int, payload: dict, side_effecting: bool) -> None:
        self.events[event_id] = payload
        if side_effecting:
            self.committed_side_effects.add(event_id)

    def evict(self, event_id: int) -> None:
        if event_id in self.committed_side_effects and event_id > self.acked_floor:
            raise StreamResumptionViolation(
                f"refusing to evict event {event_id}: side effect committed but "
                f"client ack floor is {self.acked_floor}; eviction would orphan "
                f"the result and enable duplicate execution on retry"
            )
        self.events.pop(event_id, None)

    def replay_from(self, last_event_id: int) -> list[dict]:
        retained = sorted(self.events)
        if not retained:
            raise StreamResumptionViolation(
                f"session buffer empty; cannot replay from {last_event_id}"
            )
        floor = retained[0]
        if last_event_id < floor - 1:
            # The client's last-processed id is below what we still hold.
            # A gap exists that we cannot fill.
            raise StreamResumptionViolation(
                f"replay gap: client requested events after {last_event_id}, "
                f"but retained floor is {floor}; events in ({last_event_id}, "
                f"{floor}) were evicted before ack — session must be treated "
                f"as poisoned and in-flight tool calls reconciled out-of-band"
            )
        return [self.events[e] for e in retained if e > last_event_id]

    def ack(self, event_id: int) -> None:
        self.acked_floor = max(self.acked_floor, event_id)
        for e in [e for e in self.committed_side_effects if e <= self.acked_floor]:
            self.committed_side_effects.discard(e)
            self.events.pop(e, None)
