# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-semantic-convention-attribution-and-span-level-truth-when-a-tool-call-is-retried-under-a-new-span.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-semantic-convention-attribution-and-span-level-truth-when-a-tool-call-is-retried-under-a-new-span.warrant.json
# Markdown SHA-256:   0adba3d9ab1e9f2cb1467ec304d7c4be50758e64fd3c08b98c06e687a9aec9d6
# Code AST SHA-256:   8ab7a1ff9a1ae39111f75dab2eaae04b15cd7eb39eb93a212dddb2e570ebb67f
# Verified Classes:   AttributionInvariantError, Attempt, LogicalCall
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AttributionInvariantError(RuntimeError):
    """Raised when a span-level attribution would violate call-level cardinality."""


@dataclass
class Attempt:
    span_id: str
    tool_name: str
    response_id: Optional[str]
    input_tokens: int
    has_retrieval_child: bool


@dataclass
class LogicalCall:
    call_id: str
    tool_name: str
    attempts: list = field(default_factory=list)

    def add_attempt(self, attempt: Attempt) -> None:
        if attempt.tool_name != self.tool_name:
            raise AttributionInvariantError(
                f"attempt {attempt.span_id} tool={attempt.tool_name} "
                f"does not match call {self.call_id} tool={self.tool_name}"
            )
        self.attempts.append(attempt)

    def attributed_tokens(self) -> int:
        # Only the terminal attempt's usage is attributable to the call;
        # earlier attempts re-incurred context that must not be summed.
        if not self.attempts:
            return 0
        return self.attempts[-1].input_tokens

    def terminal_retrieval_docs(self) -> int:
        terminal = self.attempts[-1] if self.attempts else None
        if terminal is None or not terminal.has_retrieval_child:
            raise AttributionInvariantError(
                f"call {self.call_id} terminal attempt has no retrieval child span; "
                "provenance join would yield a false-negative grounding result"
            )
        return 1


def attribute(spans: list[Attempt], call_id: str) -> LogicalCall:
    if not spans:
        raise AttributionInvariantError(f"call {call_id} has zero spans; cannot attribute")
    call = LogicalCall(call_id=call_id, tool_name=spans[0].tool_name)
    for s in spans:
        call.add_attempt(s)
    # Enforce the boundary: every attempt after the first must be identifiable
    # as the same logical call, which the wrapper guarantees via call_id.
    if len(call.attempts) > 1 and not call_id:
        raise AttributionInvariantError(
            f"multi-attempt call {call_id} lacks a logical-call identity; "
            "span-level attribution would double-count"
        )
    return call
