# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-parentage-when-an-mcp-tool-spans-cross-a-trace-context-re-injection-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-parentage-when-an-mcp-tool-spans-cross-a-trace-context-re-injection-boundary.warrant.json
# Markdown SHA-256:   5bc2122ba69cc2ced2fef03d743b1c998d1f734223c1d4861b9da1862d507b03
# Code AST SHA-256:   818537ebfaacfbbbca04acd127ecaf95d20f2e299c28a1ec5975b210078ade05
# Verified Classes:   CausalParentageError, SpanContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class CausalParentageError(RuntimeError):
    """Raised when an emitted tool span's causal parent is not the active handler span."""


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


def emit_tool_span(
    *,
    handler_span: SpanContext,      # the handle_task span for THIS invocation
    active_context: SpanContext,    # ambient/cached "current span" at emit time
    inbound_traceparent: SpanContext,
    tool_name: str,
) -> SpanContext:
    # Invariant: the emitted tool span must descend from the handler span,
    # and must share the inbound trace. A stale ambient context is a bug,
    # not a fallback.
    if handler_span.trace_id != inbound_traceparent.trace_id:
        raise CausalParentageError(
            f"handler trace {handler_span.trace_id} != inbound trace "
            f"{inbound_traceparent.trace_id}; context re-injection lost trace lineage"
        )

    if active_context != handler_span:
        # Warm-pool stale context detected. Do NOT silently re-parent.
        raise CausalParentageError(
            f"emit of {tool_name}: active context span {active_context.span_id} "
            f"is not handler span {handler_span.span_id} "
            f"(stale pooled context; causal parent would be wrong)"
        )

    # Parent is unambiguously the handler span.
    return SpanContext(trace_id=handler_span.trace_id, span_id=handler_span.span_id)
