# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-child-span-when-its-parent-span-context-arrives-via-a-semantic-convention-link-rather-than-a-d.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-child-span-when-its-parent-span-context-arrives-via-a-semantic-convention-link-rather-than-a-d.warrant.json
# Markdown SHA-256:   c6d458a8a658dc337a8a17032a0c9b32958c4dfe4068db7ee22007d81323f029
# Code AST SHA-256:   c5a05fc8cff1483ce773cfb85de07e15dc618a908e1f3a0b5c266dc2ead59513
# Verified Classes:   HandoffCorrelationError, SpanContext, HandoffEnvelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

_ZERO_TRACE = "0" * 32
_ZERO_SPAN = "0" * 16


class HandoffCorrelationError(RuntimeError):
    """Raised when a link-based handoff cannot anchor a valid trace subtree."""


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str
    sampled: bool
    valid: bool


@dataclass(frozen=True)
class HandoffEnvelope:
    upstream: Optional[SpanContext]
    has_link: bool
    downstream_is_part_of_upstream_task: bool


def materialize_parent(envelope: HandoffEnvelope) -> SpanContext:
    """
    Decide whether the receiving agent may emit spans under the handoff,
    and return the SpanContext that must be used as the real parent.

    Invariant: a link alone never establishes a parent. If the downstream
    agent's work is part of the upstream task, the upstream SpanContext
    must be promoted to a true parent, or the handoff is refused.
    """
    up = envelope.upstream

    if up is None:
        raise HandoffCorrelationError(
            "handoff carries no upstream SpanContext; cannot anchor subtree"
        )

    if not up.valid or up.trace_id == _ZERO_TRACE or up.span_id == _ZERO_SPAN:
        raise HandoffCorrelationError(
            f"upstream SpanContext failed W3C validation: "
            f"trace_id={up.trace_id!r} span_id={up.span_id!r}"
        )

    if envelope.downstream_is_part_of_upstream_task and not envelope.has_link:
        # Direct parent reference: no materialization needed.
        return up

    if envelope.downstream_is_part_of_upstream_task and envelope.has_link:
        # Link-only handoff for task-coupled work: promote to parent.
        # Refuse if the upstream trace was not sampled, because emitting a
        # sampled child under an unsampled parent fragments the trace and
        # produces a subtree the backend will accept but never correlate.
        if not up.sampled:
            raise HandoffCorrelationError(
                f"refusing to emit child under unsampled upstream trace "
                f"{up.trace_id}; link-only handoff cannot propagate sampling"
            )
        return up

    # Downstream work is an independent artifact citing the upstream:
    # a link is correct and no parent is materialized here.
    raise HandoffCorrelationError(
        "independent-artifact handoff must not be parented; emit with link only"
    )
