# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-span-attribute-loss-when-opentelemetry-genai-conventions-collide-with-an-in-flight-agent-retry-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-span-attribute-loss-when-opentelemetry-genai-conventions-collide-with-an-in-flight-agent-retry-loop.warrant.json
# Markdown SHA-256:   c45fcfbedb5f95fb601e0abcd328b5792f52df4c744d5853df322c05a77d6498
# Code AST SHA-256:   cf17dda99738b913d339079560beb87052b982680486d85bb2446bc4b8b2c729
# Verified Classes:   GenAIAttributeCollisionError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any


class GenAIAttributeCollisionError(RuntimeError):
    """Raised when a span that already carries per-call gen_ai.* facts is about
    to receive a second attempt's values, which would silently overwrite the
    first attempt's token accounting and finish reasons."""


@dataclass
class Span:
    name: str
    attributes: dict[str, Any] = field(default_factory=dict)

    def set_attribute(self, key: str, value: Any) -> None:
        self.attributes[key] = value


PER_CALL_KEYS = frozenset(
    {
        "gen_ai.request.model",
        "gen_ai.usage.input_tokens",
        "gen_ai.usage.output_tokens",
        "gen_ai.response.finish_reasons",
    }
)


def record_model_call(
    span: Span,
    *,
    model: str,
    input_tokens: int,
    output_tokens: int,
    finish_reason: str,
) -> None:
    """Record one model call on a span. Enforces the one-call-per-span invariant
    for the gen_ai.* per-call attribute namespace."""
    colliding = PER_CALL_KEYS.intersection(span.attributes)
    if colliding:
        raise GenAIAttributeCollisionError(
            f"span {span.name!r} already carries per-call gen_ai.* attributes "
            f"{sorted(colliding)}; a second model call would overwrite attempt-1 "
            f"token accounting. Open a child span per attempt instead."
        )
    span.set_attribute("gen_ai.request.model", model)
    span.set_attribute("gen_ai.usage.input_tokens", input_tokens)
    span.set_attribute("gen_ai.usage.output_tokens", output_tokens)
    span.set_attribute("gen_ai.response.finish_reasons", [finish_reason])


def execute_with_fallback(step_span: Span, attempts: list[dict[str, Any]]) -> list[Span]:
    """Correct pattern: one child span per dispatched model call, parent step
    span carries only aggregate, non-gen_ai.* facts."""
    child_spans: list[Span] = []
    for i, attempt in enumerate(attempts):
        child = Span(name=f"gen_ai.chat[{i}]")
        record_model_call(
            child,
            model=attempt["model"],
            input_tokens=attempt["input_tokens"],
            output_tokens=attempt["output_tokens"],
            finish_reason=attempt["finish_reason"],
        )
        child_spans.append(child)
    step_span.set_attribute("agent.step.attempt_count", len(child_spans))
    step_span.set_attribute("agent.step.final_model", attempts[-1]["model"])
    return child_spans


if __name__ == "__main__":
    # Anti-pattern: reuse one span across a retry -> guard fires.
    reused = Span(name="gen_ai.chat")
    record_model_call(reused, model="primary-large", input_tokens=3120,
                      output_tokens=0, finish_reason="error")
    try:
        record_model_call(reused, model="fallback-small", input_tokens=2980,
                          output_tokens=640, finish_reason="stop")
    except GenAIAttributeCollisionError as exc:
        print(f"guard fired as intended: {exc}")
