# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-opentelemetry-genai-spans-whose-gen-ai-tool-call-id-is-reused-across-loop-iterations-and-why-does-the-attribute-model-it.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-opentelemetry-genai-spans-whose-gen-ai-tool-call-id-is-reused-across-loop-iterations-and-why-does-the-attribute-model-it.warrant.json
# Markdown SHA-256:   5490d22d0f65ce68b0ae607159e438a8249bda92c1d7c0598374fd555c338245
# Code AST SHA-256:   e83c1ddf0433e9c9df6b812670e313ea8a7d542ac24d32eb746da67e6732f305
# Verified Classes:   DuplicateToolCallIdError, ToolCallSpan, TraceEmitter
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import uuid
from dataclasses import dataclass, field

class DuplicateToolCallIdError(RuntimeError):
    """Raised when a tool-call span would reuse an id already bound in this trace."""

@dataclass
class ToolCallSpan:
    call_id: str
    tool_name: str
    args: dict
    status: str = "OK"

@dataclass
class TraceEmitter:
    trace_id: str
    _bound_ids: set[str] = field(default_factory=set)

    def emit_tool_call(self, provider_call_id: str | None, tool_name: str, args: dict) -> ToolCallSpan:
        # Preserve the provider-issued id; mint a fresh one only if absent.
        call_id = provider_call_id or str(uuid.uuid4())
        if call_id in self._bound_ids:
            raise DuplicateToolCallIdError(
                f"gen_ai.tool.call.id={call_id!r} already bound in trace {self.trace_id}; "
                f"tool={tool_name!r}. A call id must identify exactly one dispatch. "
                f"Do not derive the id from content (name+args hash); mint per dispatch."
            )
        self._bound_ids.add(call_id)
        return ToolCallSpan(call_id=call_id, tool_name=tool_name, args=args)

    def args_hash(self, tool_name: str, args: dict) -> str:
        # Stability for dashboards, kept separate from identity.
        canonical = f"{tool_name}:{sorted(args.items())}"
        return hashlib.sha1(canonical.encode()).hexdigest()[:16]


def run_loop(emitter: TraceEmitter, iterations: int) -> list[ToolCallSpan]:
    spans = []
    for i in range(iterations):
        # Simulate a provider that reuses an id on retry (a real provider bug).
        provider_id = "9f2c1a2b3c4d5e6f" if i < 3 else None
        try:
            spans.append(emitter.emit_tool_call(provider_id, "read_file", {"path": "config.yaml"}))
        except DuplicateToolCallIdError:
            # Runtime policy: mint a fresh id and record the provider anomaly.
            spans.append(emitter.emit_tool_call(None, "read_file", {"path": "config.yaml"}))
    return spans


if __name__ == "__main__":
    em = TraceEmitter(trace_id="trace-abc")
    out = run_loop(em, iterations=5)
    assert len({s.call_id for s in out}) == len(out), "call ids must be unique"
    print(f"emitted {len(out)} unique tool-call spans")
