# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-parent-child-span-link-when-a-nested-agent-to-agent-trace-crosses-a-genai-semantic-convention-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-parent-child-span-link-when-a-nested-agent-to-agent-trace-crosses-a-genai-semantic-convention-boundary.warrant.json
# Markdown SHA-256:   714b106058c2600b0ff045b89a2fb1699b932f7f9ec16e5f5c60c4653c76084f
# Code AST SHA-256:   978323315769aea7287637e9d202dbf5307df2b9a303fe817afb2b379b45effd
# Verified Classes:   SpanLinkRejected, GenAISpanContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SpanLinkRejected(RuntimeError):
    """Raised when a parent-child GenAI span link cannot be semantically validated."""


@dataclass(frozen=True)
class GenAISpanContext:
    span_id: str
    genai_schema_version: Optional[str]   # from tracestate key "genai"; None if absent
    reads_token_attrs: bool               # does parent accounting read gen_ai.usage.* ?
    attested: bool                        # third-party schema attested out-of-band?


# Attributes stable across all known gen_ai schema revisions; safe to read cross-version.
VERSION_INVARIANT_KEYS = frozenset({"gen_ai.operation.name", "gen_ai.provider.name"})


def validate_link(parent: GenAISpanContext, child: GenAISpanContext) -> str:
    """Return link confidence: 'full', 'partial', or raise SpanLinkRejected."""
    if child.genai_schema_version == parent.genai_schema_version and child.genai_schema_version:
        return "full"

    if not child.genai_schema_version:
        if not child.attested:
            raise SpanLinkRejected(
                f"child {child.span_id} carries no genai schema key in tracestate "
                f"and is unattested; parent {parent.span_id} cannot assume commensurability"
            )
        return "partial"

    # Schema versions differ.
    if not parent.reads_token_attrs:
        # Parent only reads version-invariant attributes; downgrade is safe.
        return "partial"

    raise SpanLinkRejected(
        f"schema mismatch: parent {parent.span_id}@{parent.genai_schema_version} "
        f"reads gen_ai.usage.* but child {child.span_id}@{child.genai_schema_version} "
        f"may use a different token key path; aggregated sum would be silently incomplete"
    )


def link_or_orphan(parent: GenAISpanContext, child: GenAISpanContext) -> str:
    try:
        return validate_link(parent, child)
    except SpanLinkRejected as exc:
        # Emit child as INTERNAL orphan with gen_ai.link.rejected event.
        return f"orphaned: {exc}"
