# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-token-accounting-when-a-gen-ai-agent-invoke-span-outlives-its-parent-trace-context-and-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-token-accounting-when-a-gen-ai-agent-invoke-span-outlives-its-parent-trace-context-and-tool-call.warrant.json
# Markdown SHA-256:   08a783ce4d12ba19af566b257331f6d48e65faac701736e83a0e115e57351b35
# Code AST SHA-256:   f8b023113914ba7f5393f7b1324945c08474c9eef726a920f2884462a178ce78
# Verified Classes:   TraceContextLossError, InvokeSpan
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import dataclasses
from typing import Optional


class TraceContextLossError(RuntimeError):
    """Raised when an agent resume cannot reconcile invoke-span lineage."""


@dataclasses.dataclass
class InvokeSpan:
    trace_id: str
    span_id: str
    segment_index: int
    input_tokens: int
    output_tokens: int
    continuation_of: Optional[tuple] = None  # (trace_id, span_id)
    children_trace_ids: frozenset = frozenset()


def reconcile_resume(
    original: InvokeSpan,
    resume_trace_id: str,
    resume_span_id: str,
    checkpointed_input_tokens: int,
    checkpointed_output_tokens: int,
    child_trace_ids: frozenset,
) -> InvokeSpan:
    """Emit the correct resume span, or fail loudly if the invariant is violated."""
    if not child_trace_ids:
        raise TraceContextLossError(
            "resume produced no child spans; cannot attribute tokens"
        )

    if resume_trace_id == original.trace_id:
        # Same trace: children must all share it; append to original aggregate.
        if child_trace_ids != frozenset({original.trace_id}):
            raise TraceContextLossError(
                f"child trace_ids {child_trace_ids} diverge from parent "
                f"{original.trace_id} within a single trace"
            )
        return dataclasses.replace(
            original,
            input_tokens=original.input_tokens + checkpointed_input_tokens,
            output_tokens=original.output_tokens + checkpointed_output_tokens,
            children_trace_ids=child_trace_ids,
        )

    # Context was lost / re-minted: must segment and link, never re-root silently.
    if checkpointed_input_tokens < 0 or checkpointed_output_tokens < 0:
        raise TraceContextLossError("checkpointed counters must be non-negative")

    return InvokeSpan(
        trace_id=resume_trace_id,
        span_id=resume_span_id,
        segment_index=original.segment_index + 1,
        input_tokens=checkpointed_input_tokens,
        output_tokens=checkpointed_output_tokens,
        continuation_of=(original.trace_id, original.span_id),
        children_trace_ids=child_trace_ids,
    )


def aggregate_task_tokens(segments: list[InvokeSpan]) -> dict:
    """Lineage-aware reducer; refuses naive sums across unlinked roots."""
    if not segments:
        raise TraceContextLossError("no segments to aggregate")
    ordered = sorted(segments, key=lambda s: s.segment_index)
    for i, seg in enumerate(ordered):
        if i == 0:
            if seg.continuation_of is not None:
                raise TraceContextLossError("segment 0 must not be a continuation")
            continue
        prev = ordered[i - 1]
        expected_link = (prev.trace_id, prev.span_id)
        if seg.continuation_of != expected_link:
            raise TraceContextLossError(
                f"segment {seg.segment_index} link {seg.continuation_of} "
                f"does not chain to segment {prev.segment_index} {expected_link}"
            )
        if len(seg.children_trace_ids) > 1:
            raise TraceContextLossError(
                f"segment {seg.segment_index} spans multiple trace_ids: "
                f"{seg.children_trace_ids}"
            )
    return {
        "input_tokens": sum(s.input_tokens for s in ordered),
        "output_tokens": sum(s.output_tokens for s in ordered),
        "segments": len(ordered),
        "trace_ids": [s.trace_id for s in ordered],
    }
