# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-streamable-http-mcp-server-silently-corrupt-per-session-tool-state-when-a-single-sse-stream-applies-backpressure.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-streamable-http-mcp-server-silently-corrupt-per-session-tool-state-when-a-single-sse-stream-applies-backpressure.warrant.json
# Markdown SHA-256:   6711b13dfc4f2ff14b79a7ff9f5ee1128eb9f81a96827aa515bc775fec5c24dc
# Code AST SHA-256:   3d064605be199294dc6bd578db28c6ab09166d3c2fabc11e2d439e9722a4ac5c
# Verified Classes:   SessionStateCorruption, ToolCall
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import asyncio
from dataclasses import dataclass


class SessionStateCorruption(RuntimeError):
    """Raised when a tool result is routed to a session other than the one
    that issued the tools/call request. Indicates temporal (ambient) session
    resolution instead of structural (captured-at-admission) addressing."""


@dataclass(frozen=True)
class ToolCall:
    session_id: str          # captured from Mcp-Session-Id at admission
    tool_name: str
    args: dict


async def dispatch_and_route(
    call: ToolCall,
    execute,                 # async (call) -> result
    route,                   # async (session_id, result) -> None
    ambient_session_ref,     # mutable holder: {"current": str}
) -> None:
    # Admission: bind session id structurally. This is the invariant.
    bound_session = call.session_id

    result = await execute(call)

    # Completion: route by the bound id, never by ambient state.
    if ambient_session_ref["current"] != bound_session:
        # The ambient field drifted while we were executing — exactly the
        # condition under which a shared writer + temporal routing swaps
        # results between sessions. Fail loudly instead of corrupting.
        raise SessionStateCorruption(
            f"tool result for session {bound_session!r} would be routed while "
            f"ambient session is {ambient_session_ref['current']!r}; "
            f"shared-writer backpressure has overwritten the session context"
        )

    await route(bound_session, result)


async def run_under_stalled_consumer() -> None:
    ambient = {"current": "A"}          # session A's SSE stream is stalled
    call_b = ToolCall("B", "write_scratch", {"path": "out.txt"})

    async def execute(c):
        # Simulate a slow tool; meanwhile session C is admitted and the
        # ambient field is overwritten because the writer is blocked on A.
        await asyncio.sleep(0.01)
        ambient["current"] = "C"
        return {"ok": True, "path": f"scratch/{c.session_id}/out.txt"}

    async def route(session_id, result):
        return None

    await dispatch_and_route(call_b, execute, route, ambient)
    # Unreachable: the guard above fires before any misrouted write.
