# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-trace-id-as-a-correlation-key-rather-than-an-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-trace-id-as-a-correlation-key-rather-than-an-identity.warrant.json
# Markdown SHA-256:   8e2952c8d907295b8464f947618b73f66f8931a22bc30de1146672b935a0a27f
# Code AST SHA-256:   496c66cc272328ef404ed6e9182f1855a57191780932f6a095627790e23b3a34
# Verified Classes:   TraceCorrelationError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TraceCorrelationError(RuntimeError):
    """Raised when a trace_id is used as an identity but retry structure is unproven."""
    pass


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    semantic_role: str
    attempt: int | None
    prompt_tokens: int
    duration_ms: float


def aggregate_tokens(spans: list[Span], trace_id: str) -> int:
    """Sum billed prompt tokens for a trace, deduplicating retried attempts.

    Treats trace_id as a correlation key, not an identity. Requires that every
    span in the trace carries an explicit attempt index; otherwise the trace's
    retry structure is unproven and aggregation would double-count.
    """
    trace_spans = [s for s in spans if s.trace_id == trace_id]
    if not trace_spans:
        return 0

    if any(s.attempt is None for s in trace_spans):
        raise TraceCorrelationError(
            f"trace {trace_id!r} contains spans without attempt metadata; "
            "trace_id cannot be treated as an identity for token aggregation"
        )

    # Keep only the terminal attempt per (semantic_role, parent) grouping key.
    terminal: dict[str, Span] = {}
    for s in trace_spans:
        key = s.semantic_role
        prev = terminal.get(key)
        if prev is None or s.attempt > prev.attempt:
            terminal[key] = s

    return sum(s.prompt_tokens for s in terminal.values())


def assert_unique_span_ids(spans: list[Span]) -> None:
    seen: set[tuple[str, str]] = set()
    for s in spans:
        key = (s.trace_id, s.span_id)
        if key in seen:
            raise TraceCorrelationError(
                f"duplicate (trace_id, span_id) = {key!r}; "
                "span_id was reused across attempts, trace store is corrupted"
            )
        seen.add(key)
