# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-deterministic-replay-of-mcp-a2a-traces-from-diverging-at-nondeterministic-tool-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-deterministic-replay-of-mcp-a2a-traces-from-diverging-at-nondeterministic-tool-boundaries.warrant.json
# Markdown SHA-256:   ad196a3ec1dc338dd64b0a114cbb5a4831b03c56574950690fbff80076b3635c
# Code AST SHA-256:   a7b85bd6aeb3a9538e192837a14b442aa046b3655da5f9aa3b511888a55a0d65
# Verified Classes:   ReplayDivergenceError, ToolCallRecord, LiveToolState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Any


class ReplayDivergenceError(RuntimeError):
    """Raised when a replayed session diverges from its recorded trace."""


@dataclass(frozen=True)
class ToolCallRecord:
    tool: str
    arguments: dict[str, Any]
    result: Any
    state_fingerprint: str  # hash of index version, cache gen, clock, seed
    notifications: list[dict[str, Any]]
    referenced_ids: frozenset[str]


@dataclass(frozen=True)
class LiveToolState:
    fingerprint: str
    referenced_ids: frozenset[str]


def replay_tool_call(
    record: ToolCallRecord,
    live_state: LiveToolState | None,
    re_invoke: callable,
) -> tuple[Any, str]:
    """
    Returns (result, status) where status is 'authoritative' or 'advisory'.
    Raises ReplayDivergenceError when the replay cannot be trusted as evidence.
    """
    if not record.notifications and record.tool not in _KNOWN_SILENT_TOOLS:
        raise ReplayDivergenceError(
            f"trace incomplete: {record.tool} has no recorded notification stream; "
            "replay would synthesize live notifications and diverge"
        )

    if live_state is None:
        # No live state available: serve from trace, mark advisory.
        return record.result, "advisory"

    if live_state.fingerprint != record.state_fingerprint:
        # External state has drifted. Re-invoking would produce a different
        # result than the recorded one; serve trace and flag.
        return record.result, "advisory"

    result = re_invoke(record.arguments)

    replayed_ids = _extract_referenced_ids(result)
    if replayed_ids != record.referenced_ids:
        raise ReplayDivergenceError(
            f"referenced-entity divergence in {record.tool}: "
            f"recorded {sorted(record.referenced_ids)} vs "
            f"replayed {sorted(replayed_ids)}; "
            "session is not a faithful replay and must not be cited as evidence"
        )

    return result, "authoritative"


def _extract_referenced_ids(result: Any) -> frozenset[str]:
    ids: set[str] = set()
    if isinstance(result, dict):
        for key in ("id", "doc_id", "ref"):
            if key in result:
                ids.add(str(result[key]))
        for value in result.values():
            ids |= _extract_referenced_ids(value)
    elif isinstance(result, list):
        for item in result:
            ids |= _extract_referenced_ids(item)
    return frozenset(ids)


_KNOWN_SILENT_TOOLS: frozenset[str] = frozenset()
