# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-resumable-stream-token-has-been-silently-rebound-to-a-different-session-affinity-shard.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-resumable-stream-token-has-been-silently-rebound-to-a-different-session-affinity-shard.warrant.json
# Markdown SHA-256:   b14f1bfbcd2b523d585cd4e22e22d0d328d5df63a6aedd980e6660f716398f40
# Code AST SHA-256:   70ba588188364d71fab46806c23c21f1299ca898cd47e93caa1ff091d8703ddf
# Verified Classes:   StreamContinuityError, ResumeToken
# Defensive Guards:   7 fail-closed invariants (zero external deps)

events = self.buffers.get(stream_id, [])
for ev in events[last_event_seq:]:
    yield ev
# buffer empty -> loop yields nothing -> stream closes normally

import hashlib
import hmac
from dataclasses import dataclass


class StreamContinuityError(RuntimeError):
    """Raised when a resume token cannot be proven to continue the same stream epoch."""


@dataclass(frozen=True)
class ResumeToken:
    session_id: str
    stream_id: str
    last_event_seq: int
    epoch: str          # execution epoch; changes if the tool is re-run from scratch
    owner_shard: str    # the ONLY shard permitted to serve this resume


def verify_resume(
    token: ResumeToken,
    presented_hmac: str,
    signing_key: bytes,
    local_shard: str,
    buffer_epoch: str | None,
    buffer_first_seq: int | None,
    buffer_last_seq: int | None,
) -> int:
    """Return the seq to resume from, or raise. Fails closed on every ambiguity.

    The three validity conditions are checked in order; any failure is a hard
    error, never an empty-success.
    """
    expected = hmac.new(
        signing_key,
        f"{token.session_id}|{token.stream_id}|{token.last_event_seq}|{token.epoch}|{token.owner_shard}".encode(),
        hashlib.sha256,
    ).hexdigest()
    if not hmac.compare_digest(expected, presented_hmac):
        raise StreamContinuityError(
            f"resume token HMAC mismatch for stream {token.stream_id}; refusing to resume"
        )

    # Condition 1: buffer locality. Only the owning shard may serve this stream.
    if local_shard != token.owner_shard:
        raise StreamContinuityError(
            f"stream {token.stream_id} is owned by shard {token.owner_shard}, "
            f"but resume landed on {local_shard}; rebinding would silently drop the buffer"
        )

    # Condition 2: we must actually possess a buffer covering last_event_seq.
    if buffer_epoch is None or buffer_first_seq is None or buffer_last_seq is None:
        raise StreamContinuityError(
            f"no buffer present on owning shard for stream {token.stream_id}; "
            f"cannot prove contiguity at seq {token.last_event_seq}"
        )

    # Condition 3: same execution epoch, and the requested offset is within the buffer.
    if buffer_epoch != token.epoch:
        raise StreamContinuityError(
            f"epoch mismatch for stream {token.stream_id}: token epoch {token.epoch}, "
            f"buffer epoch {buffer_epoch}; replay would splice two executions"
        )
    if not (buffer_first_seq <= token.last_event_seq + 1 <= buffer_last_seq + 1):
        raise StreamContinuityError(
            f"requested resume seq {token.last_event_seq + 1} outside buffer range "
            f"[{buffer_first_seq}, {buffer_last_seq}] for stream {token.stream_id}"
        )

    # Contiguity proven: the next emitted event MUST be exactly last_event_seq + 1.
    return token.last_event_seq + 1


def emit_resumed_stream(token: ResumeToken, events: list[tuple[int, str]], resume_seq: int):
    """Emit only from resume_seq; the first event must echo the identity witness."""
    emitted = 0
    for seq, payload in events:
        if seq < resume_seq:
            continue
        if emitted == 0 and seq != resume_seq:
            raise StreamContinuityError(
                f"first resumed event is seq {seq}, expected {resume_seq}; "
                f"client must abort, not treat as completion"
            )
        emitted += 1
        yield seq, payload
    if emitted == 0:
        # The cardinal sin: empty continuation closed as success.
        raise StreamContinuityError(
            f"resume produced zero events for stream {token.stream_id} at seq {resume_seq}; "
            f"closing cleanly here would be read as task completion"
        )
