# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attributes-a-tool-call-span-s-token-cost-to-the-wrong-parent-during-concurrent-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attributes-a-tool-call-span-s-token-cost-to-the-wrong-parent-during-concurrent-fan-out.warrant.json
# Markdown SHA-256:   1e9d77ded0f817014b528764999e6b985cceb809436a11d7b06f584874715c4c
# Code AST SHA-256:   4ca82e89e227e4c778cee18172ce5d4c6bc61b1217842a6c0813878ab0e7f62b
# Verified Classes:   TelemetryAttributionError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TelemetryAttributionError(RuntimeError):
    """Raised when a span tree violates the GenAI usage-attribution contract."""


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    name: str
    attributes: dict = field(default_factory=dict)
    children: list = field(default_factory=list)

    def carries_usage(self) -> bool:
        return any(k.startswith("gen_ai.usage.") for k in self.attributes)

    def is_declared_rollup(self) -> bool:
        return self.attributes.get("telemetry.rollup") is True


def validate_usage_attribution(root: Span) -> None:
    """
    Enforce: a span carrying gen_ai.usage.* must either have no descendant
    usage-bearing spans, or be explicitly marked telemetry.rollup=true.
    Otherwise parent+children double-count in cost rollups.
    """
    stack = [root]
    while stack:
        span = stack.pop()
        if span.carries_usage() and not span.is_declared_rollup():
            for child in span.children:
                if child.carries_usage():
                    raise TelemetryAttributionError(
                        f"span {span.span_id} ({span.name}) carries gen_ai.usage.* "
                        f"and has usage-bearing child {child.span_id} "
                        f"({child.name}) without telemetry.rollup=true; "
                        f"cost rollup will double-count on resume/fan-out"
                    )
        stack.extend(span.children)


def validate_resume_dedup(pre_crash: list, post_resume: list) -> None:
    """
    On checkpoint/resume, tool.call.id must be stable so dedup can collapse
    re-emitted children. Missing IDs make post-resume children indistinguishable
    from new calls.
    """
    for span in pre_crash + post_resume:
        if span.name.startswith("gen_ai.tool") and "gen_ai.tool.call.id" not in span.attributes:
            raise TelemetryAttributionError(
                f"tool span {span.span_id} missing gen_ai.tool.call.id; "
                f"resume dedup cannot collapse re-emitted children"
            )


# --- reproduction of the observed failure ---
def build_observed_tree() -> Span:
    parent = Span(
        span_id="p1",
        parent_id=None,
        name="gen_ai.agent.invoke_agent",
        attributes={
            "gen_ai.operation.name": "invoke_agent",
            "gen_ai.usage.input_tokens": 18240,  # synthesized rollup, undeclared
        },
    )
    parent.children = [
        Span("c1", "p1", "gen_ai.tool.execute_tool",
             {"gen_ai.tool.name": "search", "gen_ai.tool.call.id": "t1",
              "gen_ai.usage.input_tokens": 3100}),
        Span("c2", "p1", "gen_ai.tool.execute_tool",
             {"gen_ai.tool.name": "search", "gen_ai.tool.call.id": "t2",
              "gen_ai.usage.input_tokens": 3100}),
    ]
    return parent


if __name__ == "__main__":
    validate_usage_attribution(build_observed_tree())
