# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-opentelemetry-genai-span-attributes-have-silently-desynchronized-from-the-agent-s-actual-tool-call-and-token-sta.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-opentelemetry-genai-span-attributes-have-silently-desynchronized-from-the-agent-s-actual-tool-call-and-token-sta.warrant.json
# Markdown SHA-256:   e3dbefd0ab218dd8b19d255d2d69a6a4ea9c74e22ff1f4b67fd3acba9f97faf0
# Code AST SHA-256:   6995dae904ecf09a79089d7c25b00cb42d6e58f655de405b3b2c896379029d20
# Verified Classes:   TelemetryDesyncError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TelemetryDesyncError(RuntimeError):
    """Raised when a GenAI span's attributes are internally inconsistent
    with the event boundaries the span claims to describe."""
    pass


def validate_agent_span(span: dict) -> None:
    attrs = span.get("attributes", {})
    attempts = attrs.get("gen_ai.request.attempt_count", 1)
    tool_ids = attrs.get("gen_ai.tool.call.ids", [])
    out_tokens = attrs.get("gen_ai.usage.output_tokens", 0)
    duration_s = span.get("duration_s", 0.0)

    # Invariant 1: tool-call IDs must be unique within a span.
    if len(tool_ids) != len(set(tool_ids)):
        raise TelemetryDesyncError(
            f"duplicate gen_ai.tool.call.id within span {span.get('id')}: "
            f"{tool_ids} — retry reused step-scoped ID instead of attempt-scoped ID"
        )

    # Invariant 2: token count must be consistent with wall-clock at a
    # bounded tokens/sec ceiling. If attempts > 1, the span must have
    # emitted child spans; an aggregate token count on a single-duration
    # span is the double-counting signature.
    if attempts > 1 and not span.get("child_spans"):
        raise TelemetryDesyncError(
            f"span {span.get('id')} reports {attempts} attempts and "
            f"{out_tokens} output tokens but has no per-attempt child spans; "
            f"token attribute is an unlabeled aggregate"
        )

    # Invariant 3: token/duration plausibility bound (independent ground truth proxy).
    max_plausible = duration_s * attrs.get("tokens_per_sec_ceiling", 200.0) * attempts
    if out_tokens > max_plausible:
        raise TelemetryDesyncError(
            f"span {span.get('id')} claims {out_tokens} output tokens in "
            f"{duration_s}s across {attempts} attempts; exceeds ceiling "
            f"{max_plausible:.0f} — accumulator re-entry suspected"
        )
