# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-attributes-as-non-authoritative-for-token-accounting-across-a-resumed-agent-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-attributes-as-non-authoritative-for-token-accounting-across-a-resumed-agent-trace.warrant.json
# Markdown SHA-256:   808d47b7d4ceeacebcf41e7b6149acd91cdd60eaca7fd3fe2603e2dc516dc43e
# Code AST SHA-256:   6bfb54ea6885af63bf4ac7873f1fb91c7efad5a49f119b36f70b9156c8d73317
# Verified Classes:   UnjoinableResumeBoundary, GenAISpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class UnjoinableResumeBoundary(RuntimeError):
    """Raised when span-level GenAI token attributes cannot be safely
    summed into a logical-consumption figure because a resume boundary
    created spans with no shared task/step identity."""
    pass


@dataclass
class GenAISpan:
    trace_id: str
    span_id: str
    name: str                      # "gen_ai.chat" | "gen_ai.execute_tool"
    model: str | None = None
    input_tokens: int = 0
    output_tokens: int = 0
    tool_call_id: str | None = None
    step_id: str | None = None     # non-standard; required for safe dedupe
    task_id: str | None = None
    status: str = "OK"


def reconcile_logical_input_tokens(spans: list[GenAISpan]) -> int:
    """Return deduped logical input-token consumption.

    Refuses to return a number when a resume boundary is present but the
    spans lack the out-of-band step/task identity needed to join them.
    """
    chat_spans = [s for s in spans if s.name == "gen_ai.chat"]
    trace_ids = {s.trace_id for s in spans}

    # Detect a resume boundary: multiple traces linked only by tool_call_id.
    if len(trace_ids) > 1:
        tool_ids = {s.tool_call_id for s in spans if s.tool_call_id}
        linked = any(
            s.tool_call_id in tool_ids
            for s in spans
            if s.trace_id != next(iter(trace_ids))
        )
        if linked and any(s.step_id is None for s in chat_spans):
            raise UnjoinableResumeBoundary(
                f"Resume boundary across {len(trace_ids)} traces linked by "
                f"tool_call_id but chat spans lack gen_ai.agent.step.id; "
                f"cannot dedupe retried invocations. Refusing to emit a "
                f"logical-consumption figure from span attributes alone."
            )

    # Safe path: dedupe on (task_id, step_id); count each logical step once.
    seen: set[tuple[str, str]] = set()
    total = 0
    for s in chat_spans:
        if s.task_id is None or s.step_id is None:
            # Single-trace, no-resume case: attribute is authoritative.
            total += s.input_tokens
            continue
        key = (s.task_id, s.step_id)
        if key in seen:
            continue  # retry of an already-counted logical step
        seen.add(key)
        total += s.input_tokens
    return total
