# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-severed-token-accounting-lineage-when-otel-genai-span-attributes-are-re-emitted-by-an-intermediate-tool-call-proxy.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-severed-token-accounting-lineage-when-otel-genai-span-attributes-are-re-emitted-by-an-intermediate-tool-call-proxy.warrant.json
# Markdown SHA-256:   97dd39d1d47ccacbb185ccce5881bc2b1aeb54f55003b6355253328263e11465
# Code AST SHA-256:   5c6d6e0bb6c7a2716f779e81773e314585c1fcb735d3c417afcf7d387bd04a6f
# Verified Classes:   LineageSeveranceError, InboundLineage, EmittedSpan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Mapping, Optional


class LineageSeveranceError(RuntimeError):
    """Raised when a GenAI span is emitted as a root despite inbound traceparent,
    or when inherited gen_ai.agent.id / gen_ai.conversation.id are dropped."""


@dataclass(frozen=True)
class InboundLineage:
    traceparent_present: bool
    extracted_trace_id: Optional[str]
    extracted_span_id: Optional[str]
    inherited_agent_id: Optional[str]
    inherited_conversation_id: Optional[str]

    @property
    def has_valid_upstream(self) -> bool:
        return (
            self.traceparent_present
            and self.extracted_trace_id not in (None, "0" * 32)
            and self.extracted_span_id not in (None, "0" * 16)
        )


@dataclass(frozen=True)
class EmittedSpan:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    attributes: Mapping[str, object]
    operation_name: str


def assert_lineage_preserved(
    inbound: InboundLineage,
    emitted: EmittedSpan,
) -> None:
    """Enforce the severed-lineage invariant at emission time.

    A hop that received a valid upstream traceparent MUST emit a non-root span
    whose parent matches the extracted upstream span_id, and MUST carry forward
    gen_ai.agent.id and gen_ai.conversation.id. Any deviation is a severance.
    """
    if not emitted.operation_name.startswith("gen_ai."):
        return

    if not inbound.has_valid_upstream:
        # Legitimate lineage-rooting hop. No severance possible.
        return

    if emitted.parent_span_id in (None, "0" * 16):
        raise LineageSeveranceError(
            f"span {emitted.span_id} for {emitted.operation_name} emitted as root "
            f"despite inbound traceparent trace_id={inbound.extracted_trace_id} "
            f"span_id={inbound.extracted_span_id}; proxy dropped context extraction"
        )

    if emitted.parent_span_id != inbound.extracted_span_id:
        raise LineageSeveranceError(
            f"span {emitted.span_id} parent={emitted.parent_span_id} does not match "
            f"extracted upstream span_id={inbound.extracted_span_id}; "
            f"context was re-parented mid-hop"
        )

    if emitted.trace_id != inbound.extracted_trace_id:
        raise LineageSeveranceError(
            f"span {emitted.span_id} trace_id={emitted.trace_id} diverged from "
            f"inbound trace_id={inbound.extracted_trace_id}; lineage forked"
        )

    if inbound.inherited_agent_id is not None:
        emitted_agent = emitted.attributes.get("gen_ai.agent.id")
        if emitted_agent != inbound.inherited_agent_id:
            raise LineageSeveranceError(
                f"span {emitted.span_id} gen_ai.agent.id={emitted_agent!r} "
                f"dropped inherited value {inbound.inherited_agent_id!r}; "
                f"cost will be attributed to <unset>"
            )

    if inbound.inherited_conversation_id is not None:
        emitted_conv = emitted.attributes.get("gen_ai.conversation.id")
        if emitted_conv != inbound.inherited_conversation_id:
            raise LineageSeveranceError(
                f"span {emitted.span_id} gen_ai.conversation.id={emitted_conv!r} "
                f"dropped inherited value {inbound.inherited_conversation_id!r}; "
                f"conversation-level token rollup will under-count"
            )

    # Usage attributes must be present on the span that incurred them.
    for required in ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens"):
        if required not in emitted.attributes:
            raise LineageSeveranceError(
                f"span {emitted.span_id} missing {required}; token accounting "
                f"cannot be reconciled against provider invoice"
            )
