# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-dynamically-discovered-mcp-tool-schema-the-http-2-stream-epoch-vs-schema-generation-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-dynamically-discovered-mcp-tool-schema-the-http-2-stream-epoch-vs-schema-generation-invariant.warrant.json
# Markdown SHA-256:   955666bb27dfa12db1d84bf54cd8b717f1f8b8938f51e6d426c2078df1a8cf48
# Code AST SHA-256:   1882a0314360bc67b8ffc656ea67c2b3d1cfe279a0ffa5d42c1c2eff9c2438df
# Verified Classes:   SchemaEpochViolation, InFlightRequest, ConnectionState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class SchemaEpochViolation(RuntimeError):
    """Raised when a dynamically discovered tool schema cannot be safely bound
    to an in-flight or newly dispatched request."""


@dataclass
class InFlightRequest:
    request_id: str
    stream_id: int
    bound_generation: int


@dataclass
class ConnectionState:
    last_seen_epoch: int = -1
    goaway_seen: bool = False
    in_flight: dict[str, InFlightRequest] = field(default_factory=dict)


def bind_schema_generation(
    conn: ConnectionState,
    notification_stream_id: int,
    new_epoch: int,
    request_id: str,
    request_stream_id: int,
) -> int:
    """Decide which schema generation a request must be validated against.

    Returns the generation to bind. Raises SchemaEpochViolation when the
    client cannot prove the new epoch is ordered after the request.
    """
    if conn.goaway_seen:
        raise SchemaEpochViolation(
            f"GOAWAY observed before dispatch of {request_id}; "
            f"cannot bind epoch {new_epoch} across replica boundary"
        )

    if new_epoch <= conn.last_seen_epoch:
        raise SchemaEpochViolation(
            f"non-monotonic schema epoch: saw {new_epoch} after "
            f"{conn.last_seen_epoch}; catalog store is not linearizable"
        )

    # Requests dispatched on a stream ordered after the notification stream
    # may safely bind the new generation.
    if request_stream_id > notification_stream_id:
        conn.last_seen_epoch = new_epoch
        return new_epoch

    # Otherwise the request was already in flight under the prior generation.
    prior = conn.last_seen_epoch if conn.last_seen_epoch >= 0 else new_epoch - 1
    conn.in_flight[request_id] = InFlightRequest(
        request_id=request_id,
        stream_id=request_stream_id,
        bound_generation=prior,
    )
    return prior


def validate_response(conn: ConnectionState, request_id: str, payload: dict, schema_for_generation) -> None:
    req = conn.in_flight.pop(request_id, None)
    if req is None:
        raise SchemaEpochViolation(
            f"response for unknown request {request_id}; cannot resolve bound generation"
        )
    schema = schema_for_generation(req.bound_generation)
    missing = [k for k in schema.get("required", []) if k not in payload]
    if missing:
        # This is the exact failure mode from the incident: the response was
        # produced under a different generation than the one we tried to bind.
        raise SchemaEpochViolation(
            f"response for {request_id} missing {missing} under generation "
            f"{req.bound_generation}; schema/epoch binding was violated"
        )
