# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-collapse-in-opentelemetry-genai-agent-traces-when-tool-call-retries-overwrite-genai-token-and-cost-cou.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-collapse-in-opentelemetry-genai-agent-traces-when-tool-call-retries-overwrite-genai-token-and-cost-cou.warrant.json
# Markdown SHA-256:   816ae2370cf56dee61c55b8d5f136757106e26cd9d34bd547b1b5d78e1b06f34
# Code AST SHA-256:   314e2997d929ed2d2df37fa176a9d6dd6caec5d443f55918d90fa5af713fb718
# Verified Classes:   SpanAttributeCollapseError, GenAISpanGuard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpanAttributeCollapseError(RuntimeError):
    """Raised when a retry reuses a live GenAI span and overwrites usage/identity attributes,
    violating the write-once invariant on genai.usage.* and destroying the provider join key."""
    pass


WRITE_ONCE_PREFIXES = ("genai.usage.", "genai.tool.call.id", "genai.response.id")


class GenAISpanGuard:
    """Wraps a span; enforces write-once on usage counters and identity attributes."""

    def __init__(self, span):
        self._span = span
        self._written = set()

    def set_attribute(self, key: str, value):
        if key.startswith(WRITE_ONCE_PREFIXES) and key in self._written:
            raise SpanAttributeCollapseError(
                f"attempted overwrite of write-once attribute {key!r} on span "
                f"{self._span.name!r}; a retry that changes {key!r} must open a new "
                f"child span, not reuse this one — otherwise failed-attempt token cost "
                f"is silently dropped and provider call ids are orphaned"
            )
        self._written.add(key)
        self._span.set_attribute(key, value)


def record_attempt(guard: GenAISpanGuard, call_id: str, input_tokens: int, output_tokens: int):
    # Retry attempts that regenerate the tool call MUST use a fresh span.
    # This function is only valid for the first attempt on a given span.
    if "genai.tool.call.id" in guard._written:
        raise SpanAttributeCollapseError(
            f"span already carries call id {guard._span.attributes.get('genai.tool.call.id')!r}; "
            f"refusing to record attempt {call_id!r} on the same span — open a child span"
        )
    guard.set_attribute("genai.tool.call.id", call_id)
    guard.set_attribute("genai.usage.input_tokens", input_tokens)
    guard.set_attribute("genai.usage.output_tokens", output_tokens)
