# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-inherit-a-parent-span-broken-trace-parent-propagation-across-agent-handoff-sub-agent-spawn-and-async-task-resumption.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-inherit-a-parent-span-broken-trace-parent-propagation-across-agent-handoff-sub-agent-spawn-and-async-task-resumption.warrant.json
# Markdown SHA-256:   ed4de2219018ef3d3730bf505e5c42c9095c3ac4d84d0a6be4f09ecee511a447
# Code AST SHA-256:   2aa5862d086e1d5a1f8ca84ead625b4254500aff399539bebc2eb659bd0436a7
# Verified Classes:   SpanTopologyError, BoundaryKind, SpanContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class SpanTopologyError(RuntimeError):
    """Raised when a child span would be attached to an invalid parent edge."""


class BoundaryKind(Enum):
    SAME_PROCESS = "same_process"
    HANDOFF = "handoff"
    SPAWN = "spawn"
    RESUME = "resume"


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str
    sampled: bool
    live_in_process: bool          # True only if the tracer still holds this span open
    sampler_epoch: int             # bumped on sampler config reload
    parent_end_time: float | None  # None while the parent is still open


def decide_edge(
    parent: SpanContext,
    *,
    boundary: BoundaryKind,
    current_sampler_epoch: int,
    child_may_outlive_parent: bool,
) -> str:
    """Return 'child_of' or 'link_root'. Raise on structurally impossible edges."""
    if not parent.live_in_process:
        # Deserialized from a checkpoint/envelope: causality, not nesting.
        if boundary is BoundaryKind.SAME_PROCESS:
            raise SpanTopologyError(
                f"parent {parent.span_id} is not live but boundary claims same-process; "
                "context was deserialized and cannot be a parent"
            )
        return "link_root"

    if parent.parent_end_time is not None:
        # Parent already ended: child_of would create an orphan.
        raise SpanTopologyError(
            f"parent {parent.span_id} ended at {parent.parent_end_time}; "
            "refusing child_of edge, use link_root"
        )

    if child_may_outlive_parent and boundary in (BoundaryKind.SPAWN, BoundaryKind.HANDOFF):
        return "link_root"

    if parent.sampler_epoch != current_sampler_epoch:
        # Inherited trace_flags are stale; mint a fresh root with local sampling.
        return "link_root"

    return "child_of"


def start_child_span(parent: SpanContext, **kwargs) -> str:
    edge = decide_edge(parent, **kwargs)
    if edge == "link_root":
        # Emit a new root span carrying a Link back to the parent context.
        return f"root(trace={parent.trace_id}, link={parent.span_id})"
    return f"child_of(parent={parent.span_id})"
