# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-poisoned-mcp-server-whose-behavioral-fingerprint-has-drifted-below-the-detection-threshold-of-its-capability-manifest.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-poisoned-mcp-server-whose-behavioral-fingerprint-has-drifted-below-the-detection-threshold-of-its-capability-manifest.warrant.json
# Markdown SHA-256:   7a2a84ceb38631921bd9bb1e0f2db87b14272804cb5c7e35c228ada81916684f
# Code AST SHA-256:   07aa46529c5f802af12aa8dca099354571d76fa86c53aa8021a64ac19b553873
# Verified Classes:   SubThresholdDriftError, FrozenReference, WindowStat, FingerprintMonitor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import math
from dataclasses import dataclass, field


class SubThresholdDriftError(RuntimeError):
    """Raised when a server's behavioral fingerprint has drifted past the
    cross-instance divergence boundary while remaining inside every static
    per-instance ceiling."""


@dataclass
class FrozenReference:
    instance_id: str
    latency_p95: float
    latency_std: float
    id_entropy: float
    id_entropy_std: float
    registered_at_call: int


@dataclass
class WindowStat:
    latency_p95: float
    id_entropy: float


@dataclass
class FingerprintMonitor:
    server_id: str
    references: dict[str, FrozenReference] = field(default_factory=dict)
    static_latency_ceiling: float = 250.0
    static_entropy_ceiling: float = 5.0

    def register(self, ref: FrozenReference) -> None:
        self.references[ref.instance_id] = ref

    def _z(self, ref: FrozenReference, w: WindowStat) -> tuple[float, float]:
        z_lat = (w.latency_p95 - ref.latency_p95) / max(ref.latency_std, 1e-6)
        z_ent = (w.id_entropy - ref.id_entropy) / max(ref.id_entropy_std, 1e-6)
        return z_lat, z_ent

    def evaluate(self, window: WindowStat) -> dict[str, tuple[float, float]]:
        if len(self.references) < 2:
            raise SubThresholdDriftError(
                f"server {self.server_id}: cannot evaluate divergence with "
                f"{len(self.references)} observer(s); cross-instance invariant requires >=2"
            )
        zs = {iid: self._z(ref, window) for iid, ref in self.references.items()}

        # Static per-instance ceilings (the naive detector).
        static_fired = (
            window.latency_p95 > self.static_latency_ceiling
            or window.id_entropy > self.static_entropy_ceiling
        )

        # Cross-instance divergence (the invariant that catches ramps).
        ent_zs = [z[1] for z in zs.values()]
        lat_zs = [z[0] for z in zs.values()]
        ent_divergence = max(ent_zs) - min(ent_zs)
        lat_divergence = max(lat_zs) - min(lat_zs)
        max_abs_ent = max(abs(z) for z in ent_zs)
        max_abs_lat = max(abs(z) for z in lat_zs)

        if (max_abs_ent > 3.0 and ent_divergence > 2.5) or (
            max_abs_lat > 3.0 and lat_divergence > 2.5
        ):
            raise SubThresholdDriftError(
                f"server {self.server_id}: sub-threshold drift detected. "
                f"entropy z={ent_zs}, divergence={ent_divergence:.2f}; "
                f"latency z={lat_zs}, divergence={lat_divergence:.2f}; "
                f"static_ceiling_fired={static_fired}. Quarantine outputs "
                f"and emit signed divergence report to peer set."
            )
        return zs


def ingest_tool_result(monitor: FingerprintMonitor, window: WindowStat,
                       result_ids: list[str]) -> None:
    """Ingest a batch of tool results. Raises before any result is admitted
    to episodic memory if the fingerprint boundary is crossed."""
    try:
        monitor.evaluate(window)
    except SubThresholdDriftError:
        # Cascade: fingerprint quarantine implies memory quarantine.
        for rid in result_ids:
            _mark_tainted(monitor.server_id, rid)
        raise
    for rid in result_ids:
        _admit_to_memory(monitor.server_id, rid)


def _mark_tainted(server_id: str, rid: str) -> None:
    digest = hashlib.sha256(f"{server_id}:{rid}".encode()).hexdigest()[:16]
    # Taint ledger write; excluded from distillation.
    _ = digest


def _admit_to_memory(server_id: str, rid: str) -> None:
    _ = hashlib.sha256(f"{server_id}:{rid}".encode()).hexdigest()[:16]
