# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-genai-agent-span-token-accounting-replay-divergence-across-retried-tool-call-child-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-genai-agent-span-token-accounting-replay-divergence-across-retried-tool-call-child-spans.warrant.json
# Markdown SHA-256:   57f43aa79c33cd098cd7f0e88101a29de6275e45f6d1f4ecaa4d6ee7ab54b570
# Code AST SHA-256:   607fce62ecf1ed80130e81bbf09a65f3a303d99dae51aa43434c2ec1ec97d4c4
# Verified Classes:   AgentSpanAccountingError, ChildSpan, AgentSpan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

PER_ATTEMPT = "per_attempt"
PER_LOGICAL_STEP = "per_logical_step"


class AgentSpanAccountingError(RuntimeError):
    """Raised when an agent span cannot be closed with a replayable token total."""


@dataclass
class ChildSpan:
    span_id: str
    logical_step_id: Optional[str]
    input_tokens: int
    output_tokens: int
    succeeded: bool


@dataclass
class AgentSpan:
    span_id: str
    token_accounting: Optional[str] = None
    resumed_from_span_id: Optional[str] = None
    children: list = field(default_factory=list)
    closed: bool = False


def close_agent_span(span: AgentSpan, ledger_rule: str) -> dict:
    """
    Close an agent span, emitting token attributes only if the declared
    accounting rule can be reproduced by a replay over the frozen child set.
    """
    if span.closed:
        raise AgentSpanAccountingError(
            f"span {span.span_id} already closed; token attributes are immutable"
        )

    if span.token_accounting is None:
        # Runtime never declared a rule. If children share logical steps,
        # any total we write will be unreconcilable with one of the consumers.
        step_ids = [c.logical_step_id for c in span.children if c.logical_step_id]
        if len(step_ids) != len(set(step_ids)):
            span.closed = True
            return {
                "span_id": span.span_id,
                "gen_ai.agent.accounting_conflict": True,
                # usage attributes deliberately omitted: unknown, not wrong
            }
        span.token_accounting = PER_ATTEMPT

    if span.token_accounting == PER_LOGICAL_STEP:
        if any(c.logical_step_id is None for c in span.children):
            raise AgentSpanAccountingError(
                f"span {span.span_id} declares per_logical_step but child "
                f"{[c.span_id for c in span.children if c.logical_step_id is None]} "
                f"lacks gen_ai.agent.logical_step_id; cannot deduplicate"
            )
        # Keep the last successful attempt per logical step, else the last attempt.
        chosen: dict[str, ChildSpan] = {}
        for c in span.children:
            prior = chosen.get(c.logical_step_id)
            if prior is None or (c.succeeded and not prior.succeeded) or (
                c.succeeded == prior.succeeded
            ):
                chosen[c.logical_step_id] = c
        selected = list(chosen.values())
    elif span.token_accounting == PER_ATTEMPT:
        selected = span.children
    else:
        raise AgentSpanAccountingError(
            f"span {span.span_id} has unknown token_accounting="
            f"{span.token_accounting!r}"
        )

    if span.resumed_from_span_id == "unknown" and span.token_accounting == PER_LOGICAL_STEP:
        raise AgentSpanAccountingError(
            f"span {span.span_id} claims per_logical_step but resume origin is "
            f"unknown; logical-step join across crash boundary is unverifiable"
        )

    span.closed = True
    return {
        "span_id": span.span_id,
        "gen_ai.agent.token_accounting": span.token_accounting,
        "gen_ai.usage.input_tokens": sum(c.input_tokens for c in selected),
        "gen_ai.usage.output_tokens": sum(c.output_tokens for c in selected),
        "gen_ai.agent.resumed_from_span_id": span.resumed_from_span_id,
    }


def replay_audit(span: AgentSpan, emitted: dict) -> int:
    """Re-derive cost from the frozen child set and compare to the emitted total."""
    if "gen_ai.usage.input_tokens" not in emitted:
        raise AgentSpanAccountingError(
            f"span {span.span_id} emitted no usage total (accounting conflict); "
            f"cost is unknown and must not be summed into a ledger"
        )
    rule = emitted["gen_ai.agent.token_accounting"]
    recomputed = close_agent_span(
        AgentSpan(
            span_id=span.span_id,
            token_accounting=rule,
            resumed_from_span_id=span.resumed_from_span_id,
            children=span.children,
        ),
        ledger_rule=rule,
    )
    if recomputed["gen_ai.usage.input_tokens"] != emitted["gen_ai.usage.input_tokens"]:
        raise AgentSpanAccountingError(
            f"replay divergence on span {span.span_id}: emitted "
            f"{emitted['gen_ai.usage.input_tokens']} vs recomputed "
            f"{recomputed['gen_ai.usage.input_tokens']}"
        )
    return recomputed["gen_ai.usage.input_tokens"]
