# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-token-budget-drift-when-per-hop-slo-telemetry-is-aggregated-at-the-orchestrator.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-token-budget-drift-when-per-hop-slo-telemetry-is-aggregated-at-the-orchestrator.warrant.json
# Markdown SHA-256:   619d0cbdbff60ac3188e187fb53905903739a3c610563207f7ad30ca321d77c8
# Code AST SHA-256:   5ef05facf802ad5e8d65285061f38981261dab0a6d34a93efd1d7a4082c9be87
# Verified Classes:   HandoffBudgetViolation, HopTelemetry
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class HandoffBudgetViolation(RuntimeError):
    """Raised when a hop transfers more state than its successor can accept."""


@dataclass(frozen=True)
class HopTelemetry:
    hop_id: str
    output_tokens: int
    handoff_payload_tokens: int
    tool_call_distribution: Mapping[str, int]


SAFETY_MARGIN = 1.25


def evaluate_hop_slo(
    hop: HopTelemetry,
    successor_input_budget: int,
    baseline_distribution: Mapping[str, float],
    divergence_threshold: float = 0.35,
) -> str:
    # Regime B: transferred state exceeds successor's input budget.
    if hop.handoff_payload_tokens > successor_input_budget * SAFETY_MARGIN:
        raise HandoffBudgetViolation(
            f"hop {hop.hop_id} transferred {hop.handoff_payload_tokens} tokens "
            f"into successor budget {successor_input_budget} "
            f"(margin {SAFETY_MARGIN}x exceeded)"
        )

    # Regime A check: distribution-shape divergence, not scalar count.
    total = sum(hop.tool_call_distribution.values()) or 1
    observed = {k: v / total for k, v in hop.tool_call_distribution.items()}
    keys = set(observed) | set(baseline_distribution)
    # KL(observed || baseline) with Laplace smoothing on missing keys.
    eps = 1e-6
    kl = 0.0
    for k in keys:
        p = observed.get(k, eps)
        q = baseline_distribution.get(k, eps)
        kl += p * (p / q and __import__("math").log(p / q))
    if kl > divergence_threshold:
        return f"DRIFT:{hop.hop_id}:kl={kl:.3f}"
    return f"OK:{hop.hop_id}"
