# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-truncation-in-opentelemetry-genai-agent-traces-the-gen-ai-usage-input-tokens-desynchronization-boundar.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-truncation-in-opentelemetry-genai-agent-traces-the-gen-ai-usage-input-tokens-desynchronization-boundar.warrant.json
# Markdown SHA-256:   8cf9db9a40db2c00d39a1df5ea41a7adb2f90e5948bb7b71097064870c4052ee
# Code AST SHA-256:   734ae9e52864841189e0d795fd9a251bff18e2a7e0c963814d895b75330c5434
# Verified Classes:   TraceReconciliationError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TraceReconciliationError(RuntimeError):
    """Raised when an agent root span cannot be reconciled against its children."""
    pass


@dataclass
class Span:
    name: str
    input_tokens: int
    output_tokens: int
    operation: str  # e.g. "invoke_agent", "execute_tool"
    expected_child_count: Optional[int] = None  # witness attribute on root spans
    declared_unattributed: Optional[int] = None  # pre-computed at runtime


def reconcile(root: Span, children: list[Span]) -> dict:
    """Reconcile an agent root span against its visible children.

    Returns a dict with reconciliation status. Raises TraceReconciliationError
    only when the trace is structurally incoherent (e.g. children claim more
    tokens than the root). Truncation is reported, not raised, because it is a
    valid-but-lossy state that downstream cost jobs must handle explicitly.
    """
    if root.operation != "invoke_agent":
        raise TraceReconciliationError(
            f"reconcile() requires an invoke_agent root, got {root.operation!r}"
        )

    child_sum = sum(c.input_tokens for c in children)
    delta = root.input_tokens - child_sum

    # Structural incoherence: children cannot exceed the parent's reported usage.
    if delta < 0:
        raise TraceReconciliationError(
            f"child input_tokens ({child_sum}) exceed root ({root.input_tokens}); "
            "possible span merging or double-counted usage"
        )

    visible = len(children)
    truncated = (
        root.expected_child_count is not None
        and visible < root.expected_child_count
    )

    if truncated and root.declared_unattributed is None:
        # Truncation detected but runtime omitted the witness delta: unrecoverable.
        raise TraceReconciliationError(
            f"root declares {root.expected_child_count} children but only "
            f"{visible} exported, and no unattributed_tokens witness present; "
            "elision is undetectable downstream without runtime-side fix"
        )

    return {
        "complete": not truncated and delta == 0,
        "truncated": truncated,
        "visible_children": visible,
        "expected_children": root.expected_child_count,
        "unattributed_tokens": delta,
        "witness_consistent": (
            root.declared_unattributed is None
            or root.declared_unattributed == delta
        ),
    }
