# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-opentelemetry-genai-spans-without-a-stable-agent-instance-identity-and-cost-telemetry-detaches-from-the-trace-that.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-opentelemetry-genai-spans-without-a-stable-agent-instance-identity-and-cost-telemetry-detaches-from-the-trace-that.warrant.json
# Markdown SHA-256:   fba62a36d60303c272f6cc0ff76eab15bca5110d885da928c3ca7f6e7864ad43
# Code AST SHA-256:   5f492bb89e5c1a7bd5ed66cc1e88d63da2d4bdaa5803bd785a3b4ddf929a789e
# Verified Classes:   TelemetryAttributionError, GenAISpan, ExecutionRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TelemetryAttributionError(RuntimeError):
    """Raised when a usage-bearing GenAI span cannot be attributed to a stable execution."""
    pass


@dataclass
class GenAISpan:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    service_instance_id: str
    operation_name: str
    input_tokens: int
    output_tokens: int
    is_task_root: bool = False


@dataclass
class ExecutionRegistry:
    # execution_id -> set of live instance ids bound to it
    live_instances: dict[str, set[str]]
    # instance_id -> execution_id it was allocated to (must be unique)
    instance_owner: dict[str, str]

    def instance_is_execution_scoped(self, instance_id: str) -> bool:
        return instance_id in self.instance_owner


def validate_usage_span(
    span: GenAISpan,
    registry: ExecutionRegistry,
    trace_roots: dict[str, str],
) -> None:
    """Guardrail: reject usage-bearing spans that break cost attribution."""
    usage = span.input_tokens + span.output_tokens
    if usage <= 0:
        return  # no cost to attribute

    # (a) reachability: every usage span must have an ancestor root in its trace
    if span.trace_id not in trace_roots:
        raise TelemetryAttributionError(
            f"usage span {span.span_id} in trace {span.trace_id} has no known "
            f"task root; cost of {usage} tokens is orphaned (retry/resume minted "
            f"a new root instead of a child span)"
        )

    # (b) identity stability: instance id must be execution-scoped, not recycled
    if not registry.instance_is_execution_scoped(span.service_instance_id):
        raise TelemetryAttributionError(
            f"usage span {span.span_id} carries recycled process-scoped "
            f"service.instance.id={span.service_instance_id}; per-instance cost "
            f"aggregation would merge unrelated executions"
        )

    # (c) sub-agent spans must be parented, not independent roots
    if not span.is_task_root and span.parent_span_id is None:
        raise TelemetryAttributionError(
            f"non-root usage span {span.span_id} has no parent; sub-agent cost "
            f"cannot roll up to task root"
        )
