# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-linked-handoff-span-when-the-receiving-agent-s-semantic-convention-version-diverges-from-the-s.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-linked-handoff-span-when-the-receiving-agent-s-semantic-convention-version-diverges-from-the-s.warrant.json
# Markdown SHA-256:   5a31c7cd8b75d914abe47739363d0c8838cc55fa38301eccee76bcd470c1140f
# Code AST SHA-256:   df1315e73949df8743d5af0f8137ba19e708d602cc013c9691d717622b07abe3
# Verified Classes:   HandoffSemanticMismatch, SchemaVersion, HandoffContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class HandoffSemanticMismatch(RuntimeError):
    """Raised when a linked handoff span would claim causal continuity
    across a semantic-convention boundary that has not been reconciled."""


@dataclass(frozen=True)
class SchemaVersion:
    major: int
    minor: int


@dataclass(frozen=True)
class HandoffContext:
    sender_schema: SchemaVersion
    receiver_schema: SchemaVersion
    link_attached_before_receiver_span_end: bool
    usage_on_link: bool
    receiver_expects_usage_on_link: bool
    receiver_expects_conversation_id: bool
    sender_emits_conversation_id: bool
    explicit_downgrade: bool


def validate_handoff_link(ctx: HandoffContext) -> None:
    if ctx.sender_schema.major != ctx.receiver_schema.major:
        if not ctx.explicit_downgrade:
            raise HandoffSemanticMismatch(
                f"schema major mismatch sender={ctx.sender_schema.major} "
                f"receiver={ctx.receiver_schema.major} with no explicit "
                f"downgrade; refusing to emit semantically-linked span"
            )
    if not ctx.link_attached_before_receiver_span_end:
        raise HandoffSemanticMismatch(
            "link attached after receiver span end; would orphan link and "
            "let receiver identity win by write order"
        )
    if ctx.usage_on_link != ctx.receiver_expects_usage_on_link:
        raise HandoffSemanticMismatch(
            f"usage placement mismatch: sender_on_link={ctx.usage_on_link} "
            f"receiver_expects_on_link={ctx.receiver_expects_usage_on_link}; "
            f"usage would be double-counted or dropped"
        )
    if ctx.sender_emits_conversation_id and not ctx.receiver_expects_conversation_id:
        raise HandoffSemanticMismatch(
            "sender emits gen_ai.conversation.id but receiver schema does not "
            "recognize it; conversation correlation would be silently dropped"
        )


def emit_handoff_span(ctx: HandoffContext) -> str:
    validate_handoff_link(ctx)
    if ctx.sender_schema.major != ctx.receiver_schema.major:
        return "emit_unlinked_span_with_semantic_mismatch_tag"
    return "emit_linked_span"
