# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-genai-trace-link-when-opentelemetry-span-propagation-silently-drops-the-parent-context-and-token-accounting-becom.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-genai-trace-link-when-opentelemetry-span-propagation-silently-drops-the-parent-context-and-token-accounting-becom.warrant.json
# Markdown SHA-256:   f51e35d81d2cb8c1eaebc042c110dd504025d75baff9fc9cbb072723daf0ce36
# Code AST SHA-256:   7019aacdd145acac1196908e6a74cc1f6b039096d86c735e83676dde40261a44
# Verified Classes:   TracePropagationError, InboundContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TracePropagationError(RuntimeError):
    """Raised when a GenAI span would be emitted with a severed or duplicated trace link."""
    pass


@dataclass
class InboundContext:
    trace_id: Optional[str]
    parent_span_id: Optional[str]
    task_id: str


def begin_agent_span(ctx: InboundContext, is_task_root: bool) -> dict:
    """
    Guardrail executed BEFORE creating the first span in a receiving agent.

    Enforces two invariants:
      1. A non-root agent span must carry a resolvable parent in the same trace.
      2. The resulting span's trace_id must equal the inbound traceparent trace_id.
    """
    if not is_task_root:
        if not ctx.trace_id or not ctx.parent_span_id:
            raise TracePropagationError(
                f"Severed trace link for task {ctx.task_id!r}: "
                f"trace_id={ctx.trace_id!r}, parent_span_id={ctx.parent_span_id!r}. "
                "Refusing to re-root; emitting would double-count tokens and orphan tool spans."
            )

    # Simulate span creation; in production this is tracer.start_span(...)
    emitted_trace_id = ctx.trace_id or "NEWLY_MINTED"

    if not is_task_root and emitted_trace_id != ctx.trace_id:
        raise TracePropagationError(
            f"Trace ID drift on task {ctx.task_id!r}: "
            f"inbound trace_id={ctx.trace_id!r} but span would emit under {emitted_trace_id!r}. "
            "Async worker likely inherited a fresh Context instead of the gateway's."
        )

    return {
        "trace_id": emitted_trace_id,
        "parent_span_id": ctx.parent_span_id,
        "gen_ai.task.id": ctx.task_id,
        "gen_ai.task.root": is_task_root,
    }


def account_completion_tokens(
    span: dict,
    input_tokens: int,
    output_tokens: int,
    cache_read_tokens: int = 0,
    already_counted_in_task: bool = False,
) -> dict:
    """
    Enforces the token-accounting invariant: a completion's tokens are recorded
    exactly once per task. Re-sent shared prefixes must be tagged as cache reads,
    never added as fresh input_tokens.
    """
    if already_counted_in_task:
        raise TracePropagationError(
            f"Double-count guard tripped for task {span.get('gen_ai.task.id')!r}: "
            "this completion was already attributed under another span in the same task. "
            "Check for a severed trace link that caused re-rooting."
        )

    if cache_read_tokens > input_tokens:
        raise TracePropagationError(
            f"Invalid token accounting on task {span.get('gen_ai.task.id')!r}: "
            f"cache_read_tokens={cache_read_tokens} exceeds input_tokens={input_tokens}."
        )

    span["gen_ai.usage.input_tokens"] = input_tokens
    span["gen_ai.usage.output_tokens"] = output_tokens
    span["gen_ai.usage.cache_read_tokens"] = cache_read_tokens
    return span
