# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-tool-call-retry-mutates-the-semantic-payload-mid-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-tool-call-retry-mutates-the-semantic-payload-mid-trace.warrant.json
# Markdown SHA-256:   0c6e873d272bffbd078b7c6cf6ea370e11f0d21ef6ab53113b010e99e7455666
# Code AST SHA-256:   4ad2f9d2803377fec1d78ec4a6c883f8157d41539c4f09490d062abca7836980
# Verified Classes:   GenAISpanIdentityMutationError, ToolSpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class GenAISpanIdentityMutationError(RuntimeError):
    """Raised when a tool span's identity-bearing GenAI attributes are
    overwritten in place across a retry, breaking the one-span-one-attempt
    invariant that trace-as-memory consumers rely on."""
    pass


class ToolSpan:
    # Identity attributes that MUST be write-once for the span's lifetime.
    IDENTITY_ATTRS = ("gen_ai.tool.call.id", "gen_ai.tool.call.arguments")

    def __init__(self, call_id: str, arguments: str):
        self._attrs = {
            "gen_ai.tool.call.id": call_id,
            "gen_ai.tool.call.arguments": arguments,
        }
        self._frozen = dict(self._attrs)  # snapshot at open
        self.attempt_count = 1

    def set_attr(self, key: str, value):
        if key in self.IDENTITY_ATTRS and key in self._frozen:
            if value != self._frozen[key]:
                raise GenAISpanIdentityMutationError(
                    f"refusing to mutate {key!r} in place on a live tool span: "
                    f"was {self._frozen[key]!r}, retry wants {value!r}. "
                    f"Open a child span with a fresh gen_ai.tool.call.id "
                    f"(e.g. '{self._frozen['gen_ai.tool.call.id']}.r{self.attempt_count}') "
                    f"or declare logical-call semantics with attempt_count and "
                    f"preserved error events."
                )
        self._attrs[key] = value

    def record_retry(self, new_arguments: str):
        # A retry with a mutated payload is the trigger condition.
        self.attempt_count += 1
        self.set_attr("gen_ai.tool.call.arguments", new_arguments)


def trace_tool_attempt(span: ToolSpan, retry_arguments: str | None = None):
    if retry_arguments is not None:
        # This is exactly where naive wrappers overwrite and corrupt the trace.
        span.record_retry(retry_arguments)
    return span
