# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-genai-agent-span-attribute-loss-across-tool-call-fan-out-when-token-accounting-propagates-through-nested-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-genai-agent-span-attribute-loss-across-tool-call-fan-out-when-token-accounting-propagates-through-nested-spans.warrant.json
# Markdown SHA-256:   87aaa10f11885337ea64fbab2bdc9495b59ee5a7385453881b2fedd8f50afea8
# Code AST SHA-256:   5eb662c6d3f6fdf1de4827d0cb61efc2ab30f5e7dbe9e65767df945dcae94d81
# Verified Classes:   UsageAttributeViolation, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageAttributeViolation(RuntimeError):
    """Raised when a span attempts to set gen_ai.usage.* outside a model-call span,
    or when a usage-bearing span closes without a sourced delta."""
    pass


USAGE_KEYS = frozenset({"gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens"})
MODEL_OPS = frozenset({"chat", "text_completion", "embeddings"})


@dataclass
class Span:
    name: str
    operation: str
    attributes: dict = field(default_factory=dict)
    children: list = field(default_factory=list)
    closed: bool = False

    def set_usage(self, input_tokens: int, output_tokens: int) -> None:
        if self.operation not in MODEL_OPS:
            raise UsageAttributeViolation(
                f"span {self.name!r} op={self.operation!r} attempted to set "
                f"gen_ai.usage.* but is not a model-call span; usage must be "
                f"sourced from the provider response on a chat/completion span"
            )
        self.attributes["gen_ai.usage.input_tokens"] = input_tokens
        self.attributes["gen_ai.usage.output_tokens"] = output_tokens

    def close(self) -> None:
        if self.operation in MODEL_OPS:
            has_usage = USAGE_KEYS.issubset(self.attributes)
            marked_missing = self.attributes.get("gen_ai.usage.missing") is True
            if not has_usage and not marked_missing:
                raise UsageAttributeViolation(
                    f"model-call span {self.name!r} closed without gen_ai.usage.* "
                    f"and without gen_ai.usage.missing=true; refusing to export "
                    f"a span whose token accounting is silently absent"
                )
        self.closed = True


def aggregate_usage(root: Span) -> dict:
    """Sum usage over usage-bearing descendants. Absent != zero: only spans
    that actually carry the attribute contribute."""
    totals = {"input": 0, "output": 0, "missing_spans": 0}

    def walk(span: Span) -> None:
        if span.attributes.get("gen_ai.usage.missing") is True:
            totals["missing_spans"] += 1
        if USAGE_KEYS.issubset(span.attributes):
            totals["input"] += span.attributes["gen_ai.usage.input_tokens"]
            totals["output"] += span.attributes["gen_ai.usage.output_tokens"]
        for child in span.children:
            walk(child)

    walk(root)
    return totals


def assert_monotonic_usage(root: Span) -> None:
    """Invariant: along any root-to-leaf path, cumulative usage is
    non-decreasing, and equals the sum over usage-bearing descendants."""
    expected = aggregate_usage(root)
    path_sum = {"input": 0, "output": 0}

    def walk(span: Span) -> None:
        if USAGE_KEYS.issubset(span.attributes):
            path_sum["input"] += span.attributes["gen_ai.usage.input_tokens"]
            path_sum["output"] += span.attributes["gen_ai.usage.output_tokens"]
        for child in span.children:
            walk(child)

    walk(root)
    if path_sum != {"input": expected["input"], "output": expected["output"]}:
        raise UsageAttributeViolation(
            f"usage sum invariant broken: path={path_sum} aggregate={expected}"
        )


# --- demonstration of the guardrail firing on the observed bug ---
if __name__ == "__main__":
    root = Span(name="agent.invoke", operation="invoke_agent")
    chat = Span(name="chat", operation="chat")
    chat.set_usage(4010, 180)
    tool = Span(name="execute_tool", operation="execute_tool")
    try:
        tool.set_usage(4010, 180)  # the observed context-copy bug
    except UsageAttributeViolation as e:
        print(f"guardrail fired: {e}")
    root.children.append(chat)
    root.children.append(tool)
    chat.close()
    root.close()
    print(aggregate_usage(root))  # {'input': 4010, 'output': 180, 'missing_spans': 0}
