# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-cached-mcp-tool-schema-against-a-server-that-mutates-inputschema-in-place-without-bumping-its-version-string.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-cached-mcp-tool-schema-against-a-server-that-mutates-inputschema-in-place-without-bumping-its-version-string.warrant.json
# Markdown SHA-256:   cdf198fb851370168aade1d95d91ce9bbc62761004fa14c5d6538d6de629b2ad
# Code AST SHA-256:   2febe0e3395ca63caacc2b0cf83fa01efe6a07379d5fe9060f89397ec40a259d
# Verified Classes:   SchemaDriftUnresolved, ToolDescriptor, SchemaCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class SchemaDriftUnresolved(RuntimeError):
    """Raised when revalidation cannot reconcile a cached schema with the server's current one."""
    pass


@dataclass
class ToolDescriptor:
    name: str
    version: str
    input_schema: dict[str, Any]
    epoch: str  # server-controlled token: ETag / Last-Modified / initialize hash


@dataclass
class SchemaCache:
    _store: dict[str, ToolDescriptor] = field(default_factory=dict)
    _derived_beliefs: dict[str, dict[str, Any]] = field(default_factory=dict)

    def get(self, name: str, epoch: str) -> ToolDescriptor:
        d = self._store.get(name)
        if d is None or d.epoch != epoch:
            raise SchemaDriftUnresolved(
                f"cache miss or epoch change for {name!r}: cached={getattr(d,'epoch',None)!r} live={epoch!r}"
            )
        return d

    def revalidate(self, fresh: ToolDescriptor) -> bool:
        """Returns True if drift was detected and resolved. Invalidates derived beliefs on drift."""
        old = self._store.get(fresh.name)
        drifted = old is None or old.input_schema != fresh.input_schema
        self._store[fresh.name] = fresh
        if drifted and fresh.name in self._derived_beliefs:
            # Critical: schema refresh alone is insufficient; learned defaults must die too.
            del self._derived_beliefs[fresh.name]
        return drifted


def dispatch_with_drift_guard(
    cache: SchemaCache,
    name: str,
    live_epoch: str,
    args: dict[str, Any],
    call_fn,
    fetch_fn,
) -> Any:
    try:
        desc = cache.get(name, live_epoch)
        return call_fn(desc, args)
    except SchemaDriftUnresolved:
        pass  # fall through to revalidate

    fresh = fetch_fn(name)
    if fresh.epoch != live_epoch:
        raise SchemaDriftUnresolved(
            f"epoch race for {name!r}: fetch returned {fresh.epoch!r}, expected {live_epoch!r}"
        )
    cache.revalidate(fresh)

    # Rebuild args from fresh schema; do not reuse planner-derived defaults.
    rebuilt = {k: v for k, v in args.items() if k in fresh.input_schema.get("properties", {})}
    try:
        return call_fn(fresh, rebuilt)
    except Exception as exc:
        raise SchemaDriftUnresolved(
            f"post-revalidation call to {name!r} still failed; escalate, do not loop: {exc}"
        ) from exc
