# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-convention-drift-when-a-tool-call-span-s-gen-ai-usage-output-tokens-diverges-from-the-emitted-tool-arguments-unde.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-convention-drift-when-a-tool-call-span-s-gen-ai-usage-output-tokens-diverges-from-the-emitted-tool-arguments-unde.warrant.json
# Markdown SHA-256:   b13f37a99a44d66dded1b4c2f8ed902d5003222ccf0f023684b9f2d05bd899e4
# Code AST SHA-256:   ca458421e53d2c5293f218331785ab726bdd8724a40366d29981b85fe6c5a7c3
# Verified Classes:   UnreconcilableUsageError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class UnreconcilableUsageError(RuntimeError):
    """Raised when a tool-call span's output_tokens cannot be reconciled
    with either its recorded arguments or its child-span token sum."""
    pass


@dataclass
class GenAISpan:
    operation_name: str
    tool_call_id: str
    output_tokens: int
    argument_token_estimate: int
    finish_reasons: list[str]
    child_output_tokens: list[int]
    retry_count: int | None = None


# One model response's worth of slack when comparing summed tokens to the
# argument-derived estimate. Anything beyond this is a collapsed retry loop.
MAX_SINGLE_RESPONSE_TOKENS = 4096
ROUNDING_TOLERANCE = 8


def reconcile_tool_span(span: GenAISpan) -> str:
    if span.operation_name != "execute_tool":
        raise UnreconcilableUsageError(
            f"span {span.tool_call_id}: not a tool span ({span.operation_name})"
        )
    if not span.finish_reasons:
        raise UnreconcilableUsageError(
            f"span {span.tool_call_id}: finish_reasons empty; span may be mid-stream"
        )

    child_sum = sum(span.child_output_tokens)

    # Path (a): attempt-scoped accounting.
    if abs(span.output_tokens - span.argument_token_estimate) <= MAX_SINGLE_RESPONSE_TOKENS:
        if span.child_output_tokens and abs(child_sum - span.output_tokens) > ROUNDING_TOLERANCE:
            raise UnreconcilableUsageError(
                f"span {span.tool_call_id}: aggregated output_tokens={span.output_tokens} "
                f"!= child sum={child_sum} (rounding tol {ROUNDING_TOLERANCE})"
            )
        return "attempt_scoped"

    # Path (b): logical-call accounting via child spans.
    if span.child_output_tokens and abs(child_sum - span.output_tokens) <= ROUNDING_TOLERANCE:
        return "logical_call"

    # Neither path closes. This is the collapsed-retry signature.
    raise UnreconcilableUsageError(
        f"span {span.tool_call_id}: output_tokens={span.output_tokens} exceeds "
        f"argument estimate={span.argument_token_estimate} by more than one response "
        f"({MAX_SINGLE_RESPONSE_TOKENS}) with child_sum={child_sum}; "
        f"retry_count={span.retry_count}; arguments are post-retry and untrusted"
    )


def audit_spans(spans: list[GenAISpan]) -> list[str]:
    verdicts = []
    for s in spans:
        try:
            verdicts.append(f"{s.tool_call_id}: {reconcile_tool_span(s)}")
        except UnreconcilableUsageError as e:
            verdicts.append(f"{s.tool_call_id}: QUARANTINE ({e})")
    return verdicts
