# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-span-cardinality-before-opentelemetry-genai-attributes-become-lossy-under-retry-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-span-cardinality-before-opentelemetry-genai-attributes-become-lossy-under-retry-fan-out.warrant.json
# Markdown SHA-256:   3d3efacfd65e91f80775d88c2347e2ea6ade8e74dea5606a47c2eb5494bd2bad
# Code AST SHA-256:   87e5a1438c776e3ad55e9d4246d4a63aca1813441f901af83845154a12a4518e
# Verified Classes:   SpanTopologyViolation, LogicalStep, SpanEmitter
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpanTopologyViolation(RuntimeError):
    """Raised when a retry/discard span is emitted without logical-step linkage,
    making the trace lossy under convention-naive aggregation."""
    pass


@dataclass
class LogicalStep:
    step_id: str
    attempt: int = 1
    discarded: bool = False


@dataclass
class SpanEmitter:
    # Convention-compliant GenAI attributes are emitted per span.
    # Agent-layer linkage attributes are REQUIRED for retries/discards.
    emitted_step_ids: dict = field(default_factory=dict)

    def emit_invocation(
        self,
        step: LogicalStep,
        gen_ai_operation: str,
        gen_ai_model: str,
        input_tokens: int,
        finish_reason: str,
        linkage_attr: Optional[str] = None,
    ) -> dict:
        is_retry_or_discard = step.attempt > 1 or step.discarded
        if is_retry_or_discard and linkage_attr is None:
            raise SpanTopologyViolation(
                f"step {step.step_id!r} attempt={step.attempt} discarded={step.discarded} "
                f"emitted without linkage attribute; trace will be lossy under "
                f"convention-naive aggregation (retry indistinguishable from fan-out)"
            )
        span = {
            "gen_ai.operation.name": gen_ai_operation,
            "gen_ai.request.model": gen_ai_model,
            "gen_ai.usage.input_tokens": input_tokens,
            "gen_ai.response.finish_reasons": [finish_reason],
            "agent.step.id": step.step_id,
            "agent.step.attempt": step.attempt,
            "agent.step.discarded": step.discarded,
        }
        if linkage_attr is not None:
            span["agent.retry.of"] = linkage_attr
        self.emitted_step_ids.setdefault(step.step_id, 0)
        self.emitted_step_ids[step.step_id] += 1
        return span

    def assert_trace_fidelity(self, expected_logical_steps: int) -> None:
        # Invariant: logical step count must equal distinct agent.step.id values,
        # NOT the number of emitted spans.
        distinct = len(self.emitted_step_ids)
        if distinct != expected_logical_steps:
            raise SpanTopologyViolation(
                f"trace has {distinct} distinct logical steps but agent executed "
                f"{expected_logical_steps}; replay will diverge from executor graph"
            )


# Trigger: a discarded truncated generation re-issued without linkage.
emitter = SpanEmitter()
emitter.emit_invocation(
    step=LogicalStep(step_id="s1", attempt=1),
    gen_ai_operation="chat", gen_ai_model="gpt-4o",
    input_tokens=1200, finish_reason="length",
)
# Second attempt of the SAME logical step, discarded, no linkage -> violation.
emitter.emit_invocation(
    step=LogicalStep(step_id="s1", attempt=2, discarded=True),
    gen_ai_operation="chat", gen_ai_model="gpt-4o",
    input_tokens=1200, finish_reason="stop",
    linkage_attr=None,  # <-- omission that makes the trace lossy
)
