# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-and-survive-cross-process-genai-span-conflation-when-opentelemetry-token-counters-are-keyed-by-model-name-rather-than-by-i.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-and-survive-cross-process-genai-span-conflation-when-opentelemetry-token-counters-are-keyed-by-model-name-rather-than-by-i.warrant.json
# Markdown SHA-256:   094d0212b2c5382c4305109ba2f86314ebd9272602e18fbb4f42780b35e612ee
# Code AST SHA-256:   afb1cf9d0f88265c9936a02aa68038447586da76d2b0423c5b4990ed8019e092
# Verified Classes:   InvocationIdentityError, GenAiSpanEmitter
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class InvocationIdentityError(RuntimeError):
    """Raised when a GenAI span cannot be safely attributed to a unique invocation."""
    pass


class GenAiSpanEmitter:
    def __init__(self, tracer, checkpoint_store):
        self.tracer = tracer
        self.checkpoint_store = checkpoint_store

    def emit_chat_span(self, *, model, operation, input_tokens, output_tokens,
                       trace_id, resume_from=None, is_retry=False, replay_of=None):
        # Resolve invocation identity BEFORE emitting. This is the decision boundary.
        if resume_from is not None:
            invocation_id = self.checkpoint_store.get_invocation_id(resume_from)
            if invocation_id is None:
                raise InvocationIdentityError(
                    f"resume_from={resume_from!r} has no persisted invocation.id; "
                    "cannot distinguish replay from new call, refusing to emit"
                )
            replay_of = replay_of or invocation_id
        elif is_retry:
            invocation_id = self.checkpoint_store.get_last_invocation_id(trace_id, model, operation)
            if invocation_id is None:
                raise InvocationIdentityError(
                    "retry flagged but no prior invocation.id recorded for "
                    f"(trace={trace_id}, model={model}, op={operation}); "
                    "aggregation would double-count"
                )
        else:
            invocation_id = self.checkpoint_store.mint_invocation_id(trace_id, model, operation)

        if not invocation_id:
            raise InvocationIdentityError("invocation.id resolved empty; aborting emission")

        attrs = {
            "gen_ai.system": "openai",
            "gen_ai.request.model": model,
            "gen_ai.operation.name": operation,
            "gen_ai.usage.input_tokens": input_tokens,
            "gen_ai.usage.output_tokens": output_tokens,
            "invocation.id": invocation_id,  # the disambiguator the conventions omit
        }
        if replay_of:
            attrs["gen_ai.replay_of"] = replay_of

        with self.tracer.start_as_current_span("gen_ai.chat", attributes=attrs) as span:
            self.checkpoint_store.record_invocation(trace_id, invocation_id, model, operation)
            return invocation_id
