# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-semantic-convention-drift-across-genai-telemetry-versions-without-conflating-schema-evolution-with-genuine-agent-regress.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-semantic-convention-drift-across-genai-telemetry-versions-without-conflating-schema-evolution-with-genuine-agent-regress.warrant.json
# Markdown SHA-256:   05dba8e921f879de00c337b7d369f4b45b317309c81420c6538cd91bcc831d09
# Code AST SHA-256:   ec110caab27fc645d0f055ae33d79b05ca32eb550199b4823be8df475a8dfa09
# Verified Classes:   SemanticDriftError, AttributeFingerprint, CanaryResult, DriftGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class SemanticDriftError(RuntimeError):
    """Raised when a telemetry attribute's behavioral contract cannot be verified
    equal to the contract under which a downstream threshold was calibrated."""


@dataclass(frozen=True)
class AttributeFingerprint:
    name: str
    type: str
    unit: str
    aggregation_window: str   # e.g. "per_call", "per_session_cumulative"
    cardinality_basis: str    # e.g. "per_request", "per_session"

    def digest(self) -> str:
        payload = "|".join(
            [self.name, self.type, self.unit,
             self.aggregation_window, self.cardinality_basis]
        )
        return hashlib.sha256(payload.encode()).hexdigest()[:16]


@dataclass
class CanaryResult:
    attribute: str
    expected_value: float
    observed_value: float
    tolerance: float

    @property
    def consistent(self) -> bool:
        return abs(self.observed_value - self.expected_value) <= self.tolerance


class DriftGate:
    """Gates cross-epoch telemetry comparisons on verified semantic fingerprints."""

    def __init__(self, calibrated_fingerprints: dict[str, AttributeFingerprint]):
        self._calibrated = calibrated_fingerprints

    def verify(
        self,
        declared: AttributeFingerprint,
        canary: CanaryResult,
    ) -> str:
        calibrated = self._calibrated.get(declared.name)
        if calibrated is None:
            raise SemanticDriftError(
                f"no calibrated fingerprint for {declared.name}; "
                f"cannot license any comparison"
            )

        if not canary.consistent:
            # Undeclared drift: emitter semantics moved without matching the
            # declared contract. Telemetry is untrusted for self-diagnosis.
            raise SemanticDriftError(
                f"canary mismatch on {declared.name}: "
                f"expected {canary.expected_value}±{canary.tolerance}, "
                f"observed {canary.observed_value}; "
                f"declared fingerprint {declared.digest()} does not match behavior"
            )

        if declared.digest() != calibrated.digest():
            # Declared and canary-confirmed drift: quarantine and re-baseline.
            return "REBASELINE"

        return "COMPARE"

    def assert_comparable(self, declared: AttributeFingerprint, canary: CanaryResult) -> None:
        disposition = self.verify(declared, canary)
        if disposition != "COMPARE":
            raise SemanticDriftError(
                f"{declared.name}: disposition={disposition}; "
                f"cross-epoch alarm suppressed pending re-baseline"
            )


def check_zero_plausibility(
    attribute: str,
    observed_value: float,
    operation_implies_nonzero: bool,
    prior_epoch_all_nonzero: bool,
) -> None:
    """A zero on an attribute that has never been zero is a drift signal,
    not a healthy idle. Per-span lower-bound checks miss this entirely."""
    if (
        operation_implies_nonzero
        and prior_epoch_all_nonzero
        and observed_value == 0
    ):
        raise SemanticDriftError(
            f"{attribute} reported 0 on an operation that implies nonzero, "
            f"after an epoch of strictly nonzero values; "
            f"suspected cardinality-basis drift (per_call -> per_session)"
        )
