# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-opentelemetry-genai-token-accounting-silently-double-count-tool-call-output-when-gen-ai-usage-output-tokens-is-emitted-on-both.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-opentelemetry-genai-token-accounting-silently-double-count-tool-call-output-when-gen-ai-usage-output-tokens-is-emitted-on-both.warrant.json
# Markdown SHA-256:   724723f1b74cd3100c6620b163625a3d2222101534ed07dabbc5d9ed28a06d90
# Code AST SHA-256:   fdcbf49abe7f379f47beab6e30750678d0a388d7df93c90819d82f4e52919572
# Verified Classes:   TokenAccountingInvariantError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TokenAccountingInvariantError(RuntimeError):
    """Raised when gen_ai.usage.output_tokens does not form an antichain over the span tree."""


def rollup_output_tokens(spans: list[dict]) -> int:
    """
    spans: list of dicts with keys 'span_id', 'parent_span_id',
           'operation', and optional 'output_tokens'.
    Returns the deduplicated output-token total, treating a parent's value
    as an inclusive aggregate when a descendant also carries the attribute.
    """
    by_id = {s["span_id"]: s for s in spans}
    children: dict[str | None, list[str]] = {}
    for s in spans:
        children.setdefault(s.get("parent_span_id"), []).append(s["span_id"])

    def subtree_has_token(span_id: str) -> bool:
        s = by_id[span_id]
        if s.get("output_tokens") is not None:
            return True
        return any(subtree_has_token(c) for c in children.get(span_id, []))

    def own(span_id: str) -> int:
        return by_id[span_id].get("output_tokens") or 0

    def resolve(span_id: str) -> int:
        kids = children.get(span_id, [])
        child_sum = sum(resolve(c) for c in kids)
        if own(span_id) and child_sum:
            # Parent carries an inclusive aggregate; do not add.
            return max(own(span_id), child_sum)
        return own(span_id) + child_sum

    roots = children.get(None, [])
    if not roots:
        raise TokenAccountingInvariantError(
            "no root span found; trace is malformed and token rollup is undefined"
        )

    # Validate the antichain assumption before trusting the max() collapse.
    for s in spans:
        if own(s["span_id"]) and any(
            subtree_has_token(c) for c in children.get(s["span_id"], [])
        ):
            # Legal but ambiguous: parent aggregate overlaps a child leaf.
            # We resolve via max(); flag if the parent is *smaller* than
            # the child sum, which means it is not actually inclusive.
            child_sum = sum(resolve(c) for c in children.get(s["span_id"], []))
            if own(s["span_id"]) < child_sum:
                raise TokenAccountingInvariantError(
                    f"span {s['span_id']} ({s.get('operation')}) carries "
                    f"output_tokens={own(s['span_id'])} but its descendants "
                    f"sum to {child_sum}; the parent is not an inclusive "
                    f"aggregate and flat summation would be required"
                )

    return sum(resolve(r) for r in roots)
