# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-last-event-id-against-a-stateless-mcp-replica-pool-silent-event-stream-fork-on-sse-resumption.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-last-event-id-against-a-stateless-mcp-replica-pool-silent-event-stream-fork-on-sse-resumption.warrant.json
# Markdown SHA-256:   18e78fd042ff52a819eb48d3069d923c295d7b79c755f54dc48513b0c14246f1
# Code AST SHA-256:   5ebcf46d26a66f8a889bda02a927c384a6a82620ac7dba8371e0b6fa96d039ad
# Verified Classes:   ResumptionForkError, StatelessMcpReplica
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResumptionForkError(RuntimeError):
    """Raised when a Last-Event-ID cannot be reconciled against the durable event log."""
    pass


class StatelessMcpReplica:
    def __init__(self, replica_id: str, durable_log=None, local_counter: int = 0):
        self.replica_id = replica_id
        # durable_log is None for the broken (in-process-only) topology
        self.durable_log = durable_log
        self.local_counter = local_counter

    def resume(self, last_event_id: int) -> list:
        # Broken topology: no shared log, per-process counter.
        if self.durable_log is None:
            # The dangerous silent path: reset to local counter.
            # We refuse it rather than fork the stream.
            raise ResumptionForkError(
                f"replica {self.replica_id} has no durable log; cannot verify "
                f"Last-Event-ID={last_event_id}. Refusing to reset-and-resume "
                f"(would splice divergent histories). Re-issue request from scratch."
            )

        # Durable topology: verify the cursor exists in the shared log.
        if not self.durable_log.contains(last_event_id):
            raise ResumptionForkError(
                f"Last-Event-ID={last_event_id} not present in durable log "
                f"(evicted or never emitted). Cannot resume; client must restart."
            )

        replay = self.durable_log.events_after(last_event_id)
        # Contiguity invariant: replay must be strictly monotonic with no gaps.
        expected = last_event_id + 1
        for ev in replay:
            if ev.id != expected:
                raise ResumptionForkError(
                    f"durable log gap: expected id {expected}, got {ev.id}. "
                    f"Log is corrupt or partially replicated."
                )
            expected += 1
        return replay


def handle_sse_resume(replica: StatelessMcpReplica, last_event_id: int) -> list:
    if last_event_id < 0:
        raise ResumptionForkError(f"invalid Last-Event-ID={last_event_id}")
    return replica.resume(last_event_id)
