# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-token-cost-telemetry-correlation-break-when-otel-genai-agent-spans-straddle-tool-call-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-token-cost-telemetry-correlation-break-when-otel-genai-agent-spans-straddle-tool-call-boundaries.warrant.json
# Markdown SHA-256:   ed2913f5586e4316a936600be04ab229ddbad54df73b2e92a4aa595141a2a507
# Code AST SHA-256:   bc81840c89f31bc0793d087a12b2fd9c7bfd93c4a029e17a69152fc53dd358f8
# Verified Classes:   UsageCorrelationError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageCorrelationError(RuntimeError):
    """Raised when GenAI usage attributes cannot be unambiguously correlated to cost."""
    pass


@dataclass
class GenAISpan:
    span_id: str
    parent_id: Optional[str]
    operation_name: str  # e.g. "invoke_agent", "execute_tool", "chat"
    input_tokens: Optional[int] = None
    output_tokens: Optional[int] = None
    rollup_policy: Optional[str] = None  # "exclusive" | "inclusive" | None
    children: list = field(default_factory=list)

    @property
    def has_usage(self) -> bool:
        return self.input_tokens is not None or self.output_tokens is not None

    @property
    def total_tokens(self) -> int:
        return (self.input_tokens or 0) + (self.output_tokens or 0)


def _walk(span: GenAISpan):
    yield span
    for c in span.children:
        yield from _walk(c)


def validate_usage_correlation(root: GenAISpan) -> int:
    """
    Enforce the shape invariant: usage-bearing spans form an antichain,
    OR every usage-bearing ancestor declares inclusive rollup and equals
    the sum of its usage-bearing descendants.

    Returns the attributable token total for the turn.
    """
    all_spans = list(_walk(root))
    usage_spans = [s for s in all_spans if s.has_usage]

    for ancestor in usage_spans:
        descendants = [d for d in _walk(ancestor) if d is not ancestor and d.has_usage]
        if not descendants:
            continue  # leaf usage: unambiguous

        # Ancestor and descendant both carry usage: require declared policy.
        if ancestor.rollup_policy is None:
            raise UsageCorrelationError(
                f"span {ancestor.span_id} ({ancestor.operation_name}) carries "
                f"gen_ai.usage.* and has {len(descendants)} usage-bearing "
                f"descendant(s) but declares no rollup_policy; cost is undefined"
            )

        descendant_sum = sum(d.total_tokens for d in descendants)

        if ancestor.rollup_policy == "inclusive":
            if ancestor.total_tokens != descendant_sum:
                raise UsageCorrelationError(
                    f"span {ancestor.span_id} declares inclusive rollup but "
                    f"usage {ancestor.total_tokens} != descendant sum "
                    f"{descendant_sum} (delta {ancestor.total_tokens - descendant_sum})"
                )
        elif ancestor.rollup_policy == "exclusive":
            # Exclusive ancestor must NOT equal the descendant sum unless
            # it genuinely had zero own-invocation tokens; a coincidental
            # equality signals an exporter that is actually rolling up.
            if ancestor.total_tokens == descendant_sum and descendant_sum > 0:
                raise UsageCorrelationError(
                    f"span {ancestor.span_id} declares exclusive rollup but "
                    f"usage equals descendant sum {descendant_sum}; exporter "
                    f"likely switched to inclusive without a policy update"
                )
        else:
            raise UsageCorrelationError(
                f"span {ancestor.span_id} has unknown rollup_policy "
                f"{ancestor.rollup_policy!r}"
            )

    # Attributable total: sum of usage-bearing spans that are not
    # inclusive-rollup ancestors (avoid double counting).
    total = 0
    for s in usage_spans:
        if s.rollup_policy == "inclusive":
            continue  # accounted for by descendants
        total += s.total_tokens
    return total


if __name__ == "__main__":
    # Reproduction of the observed trace: root exclusive, three model-bearing tools.
    rerank = GenAISpan("s-rr", "s-tool3", "chat", input_tokens=1623, output_tokens=0)
    tool3 = GenAISpan("s-tool3", "s-root", "execute_tool", children=[rerank])
    tool2 = GenAISpan("s-tool2", "s-root", "execute_tool", input_tokens=1540, output_tokens=0)
    tool1 = GenAISpan("s-tool1", "s-root", "execute_tool", input_tokens=1102, output_tokens=0)
    root = GenAISpan(
        "s-root", None, "invoke_agent",
        input_tokens=1435, output_tokens=412,
        rollup_policy="exclusive",
        children=[tool1, tool2, tool3],
    )
    # Root is exclusive with no usage-bearing descendants *except* rerank,
    # so the antichain is violated and policy is declared -> passes.
    # The silent-bug case: drop the policy declaration.
    root.rollup_policy = None
    try:
        validate_usage_correlation(root)
    except UsageCorrelationError as e:
        print(f"BLOCKED: {e}")
