# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-causal-trace-when-head-based-sampling-splits-an-mcp-tool-call-fan-out-across-sub-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-causal-trace-when-head-based-sampling-splits-an-mcp-tool-call-fan-out-across-sub-agents.warrant.json
# Markdown SHA-256:   b301aef678b6201ecb605afbf31c18aecc0a6a5705e2fb0aa5c30fe3a577a174
# Code AST SHA-256:   859a02b75a6769494bf04bb13cc4eace09d1ce6c03c7bb890236a3616e02ab8c
# Verified Classes:   BrokenCausalTrace, SpanContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class BrokenCausalTrace(RuntimeError):
    """Raised when a span starts without a valid parent and without an explicit root declaration."""


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


def start_span(
    *,
    name: str,
    inbound: Optional[SpanContext],
    declared_root_reason: Optional[str],
    sampler_is_parent_based: bool,
) -> SpanContext:
    # Invariant: a span is either (a) a child of an extracted inbound context,
    # or (b) an explicit root with a recorded reason. Anything else is a broken edge.
    if inbound is None and declared_root_reason is None:
        raise BrokenCausalTrace(
            f"span {name!r} has no inbound context and no declared root reason; "
            "this is an orphaned causal edge, not a root"
        )

    if inbound is not None and not sampler_is_parent_based:
        # A hop that re-decides sampling locally destroys the parent edge even
        # when it happens to sample. Reject rather than silently fork a root.
        raise BrokenCausalTrace(
            f"span {name!r} received inbound trace {inbound.trace_id!r} but its "
            "sampler is not ParentBased; local re-decision would orphan this edge"
        )

    if inbound is not None:
        # Child inherits parent's sampling decision verbatim.
        return SpanContext(
            trace_id=inbound.trace_id,
            span_id=_new_span_id(),
            sampled=inbound.sampled,
        )

    # Explicit root: sampling decision is made here, once, and recorded.
    return SpanContext(trace_id=_new_trace_id(), span_id=_new_span_id(), sampled=True)


def _new_span_id() -> str:
    import secrets
    return secrets.token_hex(8)


def _new_trace_id() -> str:
    import secrets
    return secrets.token_hex(16)
