# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-a-parent-span-cross-process-trace-context-propagation-loss-in-opentelemetry-genai-agent-spans-during-tool-call-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-a-parent-span-cross-process-trace-context-propagation-loss-in-opentelemetry-genai-agent-spans-during-tool-call-fan-out.warrant.json
# Markdown SHA-256:   8ca58f45d6abd0129069c71e2c28660e97e5201618c6d8a96be5369528034f2c
# Code AST SHA-256:   7579e684db5449938e02ec54ad022ace6dbb097c8f72e1149eea2f6e24b4d64c
# Verified Classes:   PropagationLossError, DispatchEnvelope
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class PropagationLossError(RuntimeError):
    """Raised when a tool-call dispatch cannot carry a valid trace context."""


_TRACEPARENT_RE = re.compile(
    r"^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$"
)


@dataclass(frozen=True)
class DispatchEnvelope:
    tool_name: str
    args_json: str
    traceparent: str | None
    tracestate: str | None
    conversation_id: str | None


def build_dispatch_envelope(
    tool_name: str,
    args_json: str,
    live_traceparent: str | None,
    live_tracestate: str | None,
    live_conversation_id: str | None,
    is_retry: bool,
) -> DispatchEnvelope:
    """Construct an envelope for a tool dispatch from LIVE execution state.

    The invariant: traceparent and tracestate must come from the active
    Context at dispatch time. If we are on a retry path that reconstructed
    state from a persisted record, the context may be absent -- in which
    case we must fail closed rather than let the worker start a root span.
    """
    if not live_traceparent:
        raise PropagationLossError(
            f"dispatch of tool={tool_name!r} (retry={is_retry}) has no "
            "traceparent; refusing to emit an orphan root span"
        )

    match = _TRACEPARENT_RE.match(live_traceparent)
    if not match:
        raise PropagationLossError(
            f"malformed traceparent for tool={tool_name!r}: "
            f"{live_traceparent!r}"
        )

    # A join key must survive for reconciliation to be possible. If the
    # conversation id lived only in tracestate and tracestate was lost,
    # cost attribution is permanently broken -- fail closed.
    if not live_conversation_id and not live_tracestate:
        raise PropagationLossError(
            f"tool={tool_name!r} has neither conversation_id nor "
            "tracestate; orphaned usage would be unattributable"
        )

    return DispatchEnvelope(
        tool_name=tool_name,
        args_json=args_json,
        traceparent=live_traceparent,
        tracestate=live_tracestate,
        conversation_id=live_conversation_id,
    )


def reconcile_trace_cost(root_usage: int, descendant_usages: list[int],
                         tolerance: float = 0.02) -> None:
    """Guardrail: verify per-trace usage rollup matches root accounting."""
    total = sum(descendant_usages)
    if root_usage == 0:
        raise PropagationLossError("root span reports zero usage; cannot reconcile")
    drift = abs(total - root_usage) / root_usage
    if drift > tolerance:
        raise PropagationLossError(
            f"usage reconciliation failed: root={root_usage} "
            f"descendants={total} drift={drift:.1%} > {tolerance:.0%}"
        )
