# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-streamable-transport-session-reattachment-from-silently-forking-an-agent-s-tool-call-history.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-streamable-transport-session-reattachment-from-silently-forking-an-agent-s-tool-call-history.warrant.json
# Markdown SHA-256:   08238ba55176195ef68a9f9b4dc3ec7a4be41a6d86ef0b23ed1aea94c33a25d5
# Code AST SHA-256:   dc4042645278ab6d7566e6961b5002adf232f8df41198fcdb94193ee7e4584f7
# Verified Classes:   StreamContinuityError, EventBuffer, ClientLedger
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class StreamContinuityError(RuntimeError):
    """Raised when a resumed/reattached MCP stream cannot prove causal continuity."""
    pass


@dataclass
class EventBuffer:
    session_id: str
    incarnation: str          # bumped on any server restart / counter reset
    min_retained_id: int
    max_emitted_id: int
    retained: dict = field(default_factory=dict)  # id -> payload


@dataclass
class ClientLedger:
    session_id: str
    incarnation: str
    last_acked_id: int
    pending_calls: dict = field(default_factory=dict)  # call_id -> "PENDING"


def reattach(buf: EventBuffer, ledger: ClientLedger, last_event_id: int | None) -> list:
    """
    Server-side reattachment decision. Returns the events the client may trust.
    Raises StreamContinuityError when the client would otherwise silently fork.
    """
    if buf.session_id != ledger.session_id:
        raise StreamContinuityError(
            f"session mismatch: server={buf.session_id} client={ledger.session_id}"
        )

    # ABA guard: same session id, different event-sequence incarnation.
    if buf.incarnation != ledger.incarnation:
        raise StreamContinuityError(
            "session id reused across event-sequence reset; "
            "cannot honor resume point (ABA hazard)"
        )

    if last_event_id is None:
        # Pure reattach: client must re-derive state, not trust ledger.
        for call_id in ledger.pending_calls:
            ledger.pending_calls[call_id] = "UNKNOWN"
        raise StreamContinuityError(
            "reattach without Last-Event-ID: in-flight history unknown; "
            "client must reconcile before trusting PENDING calls"
        )

    if last_event_id < buf.min_retained_id - 1:
        # Buffer evicted past the requested resume point. Head-resume here
        # is the silent-fork bug; refuse instead.
        for call_id in ledger.pending_calls:
            ledger.pending_calls[call_id] = "UNKNOWN"
        raise StreamContinuityError(
            f"Last-Event-ID {last_event_id} below retained floor "
            f"{buf.min_retained_id}; causal gap cannot be closed"
        )

    if last_event_id > buf.max_emitted_id:
        raise StreamContinuityError(
            f"Last-Event-ID {last_event_id} exceeds emitted {buf.max_emitted_id}"
        )

    # Verified resume: contiguous prefix provable. Deliver in order.
    return [buf.retained[i] for i in sorted(buf.retained) if i > last_event_id]


def commit_tool_result(ledger: ClientLedger, call_id: str, event_id: int) -> None:
    """Only a terminal event on a verified-contiguous stream may promote a call."""
    if ledger.pending_calls.get(call_id) == "UNKNOWN":
        raise StreamContinuityError(
            f"call {call_id} demoted to UNKNOWN; require reconciliation tool call "
            f"before result may enter agent context"
        )
    if event_id <= ledger.last_acked_id:
        raise StreamContinuityError(
            f"event {event_id} not causally after acked {ledger.last_acked_id}"
        )
    ledger.pending_calls[call_id] = "DONE"
    ledger.last_acked_id = event_id
