# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-mid-tool-call-identity-rebinding-across-mcp-session-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-mid-tool-call-identity-rebinding-across-mcp-session-boundaries.warrant.json
# Markdown SHA-256:   365def281e5454e33de21e628b916c1071aacd15e7aceb06663800165b0886cc
# Code AST SHA-256:   2cab3a237ce1888811afd3af4de37d769eff9f17fd1d0f534c801f24cee5e6f8
# Verified Classes:   IdentityRebindError, AuthSnapshot, InFlightCall, McpSession
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class IdentityRebindError(RuntimeError):
    """Raised when a re-attestation event would silently re-scope in-flight work."""


@dataclass(frozen=True)
class AuthSnapshot:
    subject: str
    claims: frozenset
    token_id: str


@dataclass
class InFlightCall:
    tool: str
    pinned: AuthSnapshot
    completed: bool = False


@dataclass
class McpSession:
    bound: AuthSnapshot
    inflight: dict = field(default_factory=dict)

    def dispatch(self, call_id: str, tool: str) -> None:
        # Pin the identity and claim set at dispatch time.
        self.inflight[call_id] = InFlightCall(tool=tool, pinned=self.bound)

    def reattest(self, new: AuthSnapshot) -> None:
        active = [c for c in self.inflight.values() if not c.completed]
        if not active:
            # Clean swap: no in-flight work to protect.
            self.bound = new
            return
        if new.subject != self.bound.subject:
            # A re-bound instance is a different principal. Refuse to inherit
            # in-flight authority; the caller must abort or quarantine.
            raise IdentityRebindError(
                f"subject changed {self.bound.subject!r} -> {new.subject!r} "
                f"with {len(active)} in-flight call(s); session must be torn down"
            )
        if new.claims != self.bound.claims:
            # Same subject, changed claims: future dispatches use the new
            # snapshot, but in-flight calls stay pinned. Log the delta; do not
            # retroactively re-scope.
            _record_claims_delta(self.bound, new, len(active))
        self.bound = new

    def complete(self, call_id: str) -> AuthSnapshot:
        call = self.inflight.get(call_id)
        if call is None:
            raise IdentityRebindError(f"unknown call {call_id!r}")
        call.completed = True
        # Audit uses the pinned snapshot, never the current bound snapshot.
        return call.pinned


def _record_claims_delta(old: AuthSnapshot, new: AuthSnapshot, n: int) -> None:
    narrowed = old.claims - new.claims
    widened = new.claims - old.claims
    # Emitted as a typed audit event; never a silent rebind.
    print(f"claims_delta session_subject={new.subject!r} "
          f"narrowed={sorted(narrowed)} widened={sorted(widened)} "
          f"pinned_calls={n}")
