# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-span-attribute-divergence-from-breaking-token-cost-correlation-across-agent-tool-call-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-span-attribute-divergence-from-breaking-token-cost-correlation-across-agent-tool-call-traces.warrant.json
# Markdown SHA-256:   f3bee08053f10d8194316179d47d607304174bda08257d5736b7524ff94ac1c9
# Code AST SHA-256:   6444b62cce7870baff49b82d760e93c2d7e8586ebf5a4f628444795f4c7d7bdf
# Verified Classes:   SpanProvenanceViolation, GenAISpan, CostLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpanProvenanceViolation(RuntimeError):
    """Raised when a span's cost-relevant attributes diverge from the
    invariant required for token/cost correlation (I1-I3)."""
    pass


@dataclass(frozen=True)
class GenAISpan:
    span_id: str
    operation: str
    request_model: str
    input_tokens: int
    output_tokens: int
    response_id: Optional[str] = None
    parent_span_id: Optional[str] = None


@dataclass
class CostLedger:
    spans: list[GenAISpan] = field(default_factory=list)
    _seen_span_models: dict[str, set[str]] = field(default_factory=dict)
    _seen_response_ids: dict[str, str] = field(default_factory=dict)

    def record(self, span: GenAISpan) -> None:
        # I1: a span_id must map to exactly one request_model.
        models = self._seen_span_models.setdefault(span.span_id, set())
        models.add(span.request_model)
        if len(models) > 1:
            raise SpanProvenanceViolation(
                f"I1 violated: span_id={span.span_id} carries multiple "
                f"gen_ai.request.model values {sorted(models)}; retry must "
                f"fork the span, not overwrite it."
            )
        # I3: a response_id must map to exactly one span_id.
        if span.response_id is not None:
            prior = self._seen_response_ids.get(span.response_id)
            if prior is not None and prior != span.span_id:
                raise SpanProvenanceViolation(
                    f"I3 violated: response_id={span.response_id} observed on "
                    f"span_id={prior} and span_id={span.span_id}; billable "
                    f"event is ambiguous for dedup."
                )
            self._seen_response_ids[span.response_id] = span.span_id
        # I2: usage must be co-located with the model that produced it.
        if span.operation == "execute_tool" and span.input_tokens > 0:
            raise SpanProvenanceViolation(
                f"I2 violated: tool span {span.span_id} carries LLM usage; "
                f"usage must live on the child chat span, not the tool span."
            )
        self.spans.append(span)

    def total_tokens(self) -> tuple[int, int]:
        return (
            sum(s.input_tokens for s in self.spans),
            sum(s.output_tokens for s in self.spans),
        )


def ingest_retry_attempt(ledger: CostLedger, original: GenAISpan,
                         fallback_model: str) -> GenAISpan:
    """Correct pattern: fork a new span for the retry, link to original."""
    if fallback_model == original.request_model:
        raise SpanProvenanceViolation(
            "fallback_model equals original; retry would be indistinguishable "
            "from a duplicate and cannot be deduped by response_id."
        )
    forked = GenAISpan(
        span_id=original.span_id + ".retry1",
        operation=original.operation,
        request_model=fallback_model,
        input_tokens=original.input_tokens,
        output_tokens=0,
        response_id=None,  # populated on completion
        parent_span_id=original.parent_span_id,
    )
    ledger.record(forked)
    return forked
