# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-span-level-cost-attribution-from-silently-misattributing-tokens-when-a-tool-call-fans-out-into-parallel-sub-agent-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-span-level-cost-attribution-from-silently-misattributing-tokens-when-a-tool-call-fans-out-into-parallel-sub-agent-spans.warrant.json
# Markdown SHA-256:   d4ef2186e0f4f8419c978e8974bf9f12f1c76b4f40c559a407f9ac54220e7059
# Code AST SHA-256:   e7787cd1c4142144f05cb5babed810589bd9294b221d312f11c4244db4094f69
# Verified Classes:   AttributionDriftError, ModelCall, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AttributionDriftError(RuntimeError):
    """Raised when a span's usage cannot be causally attributed to model calls."""
    pass


@dataclass
class ModelCall:
    call_index: int
    input_tokens: int
    output_tokens: int
    is_retry: bool = False


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    calls: list[ModelCall] = field(default_factory=list)
    expected_children: int = 0
    closed_children: int = 0

    @property
    def call_count(self) -> int:
        return len(self.calls)

    @property
    def total_input(self) -> int:
        return sum(c.input_tokens for c in self.calls)

    @property
    def total_output(self) -> int:
        return sum(c.output_tokens for c in self.calls)


def attribute_span(span: Span, children: list[Span]) -> dict:
    # Invariant 1: every span must map to >=1 explicit model call with provider usage.
    if span.call_count == 0 and not children:
        raise AttributionDriftError(
            f"span {span.span_id} has no model calls and no children; "
            f"usage would have to be synthesized (drift hazard)"
        )

    # Invariant 2: no scalar parent usage independent of children.
    # If a span has both its own calls AND children, it is a merge/batch span
    # whose own usage must be an explicit, separate call — not a batched total.
    if span.call_count > 1 and children:
        raise AttributionDriftError(
            f"span {span.span_id} issued {span.call_count} calls and has "
            f"{len(children)} children; batched usage cannot be causally split. "
            f"Split into one span per model call."
        )

    # Invariant 3: attribution only runs on a complete child set.
    if span.closed_children < span.expected_children:
        raise AttributionDriftError(
            f"span {span.span_id} has {span.closed_children}/"
            f"{span.expected_children} children closed; partial split would "
            f"silently zero out late children"
        )

    # Invariant 4: parent total == sum of children + own calls (accounting identity),
    # and every child's usage is provider-returned (causal identity).
    own_in = span.total_input
    own_out = span.total_output
    child_in = sum(c.total_input for c in children)
    child_out = sum(c.total_output for c in children)

    for c in children:
        if c.call_count == 0:
            raise AttributionDriftError(
                f"child {c.span_id} of {span.span_id} closed with zero calls; "
                f"its cost cannot be attributed and must not be estimated silently"
            )

    return {
        "span_id": span.span_id,
        "attributed_input": own_in + child_in,
        "attributed_output": own_out + child_out,
        "source": "provider_returned",
        "children": [c.span_id for c in children],
    }


def ingest(trace: dict[str, Span]) -> None:
    by_parent: dict[str, list[Span]] = {}
    for s in trace.values():
        if s.parent_id:
            by_parent.setdefault(s.parent_id, []).append(s)
    for s in trace.values():
        if s.parent_id is None:
            attribute_span(s, by_parent.get(s.span_id, []))
