# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-token-accounting-lineage-collapse-when-opentelemetry-genai-spans-are-re-parented-across-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-token-accounting-lineage-collapse-when-opentelemetry-genai-spans-are-re-parented-across-agent-handoffs.warrant.json
# Markdown SHA-256:   fc269a4fecf99da97da0db325fb3372ee81050c4af59c504909fadee47a1fdf3
# Code AST SHA-256:   d884a04a0a7eefdd580a3998a236bcaea767e7e783bb613fab9acea65e1347de
# Verified Classes:   LineageCollapseError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class LineageCollapseError(RuntimeError):
    """Raised when a GenAI span's token usage is incongruent with its parent-child topology."""
    pass


def validate_genai_lineage(span: dict) -> None:
    """
    Enforce the usage/topology congruence invariant for a single exported GenAI span.

    span keys (subset of OTel GenAI semconv):
      span_id, parent_span_id, gen_ai.request.model,
      gen_ai.usage.input_tokens, gen_ai.usage.output_tokens,
      gen_ai.agent.id, status.code
    """
    model = span.get("gen_ai.request.model")
    status = span.get("status.code", "UNSET")
    input_tokens = span.get("gen_ai.usage.input_tokens", 0)

    # Condition 1: a span that made a model call must report input tokens.
    if model and status == "OK" and input_tokens == 0:
        raise LineageCollapseError(
            f"span {span.get('span_id')} invoked model {model!r} with status OK "
            f"but reported 0 input tokens; usage was absorbed into an ancestor "
            f"(parent_span_id={span.get('parent_span_id')}). Cost lineage is broken."
        )

    # Condition 2: cross-agent parent implies explicit usage attribution.
    parent_agent = span.get("parent_gen_ai.agent.id")
    own_agent = span.get("gen_ai.agent.id")
    if parent_agent and own_agent and parent_agent != own_agent:
        if not span.get("gen_ai.usage.attribution"):
            raise LineageCollapseError(
                f"span {span.get('span_id')} is parented to agent {parent_agent!r} "
                f"but owned by agent {own_agent!r} with no gen_ai.usage.attribution; "
                f"trigger lineage and cost lineage have decoupled."
            )


def rollup_per_agent(spans: list[dict]) -> dict[str, int]:
    """Sum input tokens per agent, refusing to attribute collapsed spans."""
    totals: dict[str, int] = {}
    for s in spans:
        validate_genai_lineage(s)
        agent = s.get("gen_ai.agent.id", "<unattributed>")
        totals[agent] = totals.get(agent, 0) + s.get("gen_ai.usage.input_tokens", 0)
    return totals
