# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-token-accounting-lineage-when-a-genai-agent-span-is-re-parented-across-a-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-token-accounting-lineage-when-a-genai-agent-span-is-re-parented-across-a-tool-call-boundary.warrant.json
# Markdown SHA-256:   bf156f0ae32282db3ab049fcfc800a153381a32aef3f4bf4a20b4968f10d0e23
# Code AST SHA-256:   d6134cf929f2bfa3b01e2a64244f8574e1e76d6b42195be961fdb1df07866730
# Verified Classes:   UsageLineageError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import contextvars
from dataclasses import dataclass

# OpenTelemetry context propagation is a ContextVar under the hood.
# This models the attach/capture boundary that tool dispatch must respect.
_otel_context: contextvars.ContextVar[dict] = contextvars.ContextVar("otel_ctx", default={})


class UsageLineageError(RuntimeError):
    """Raised when a usage-bearing GenAI span cannot prove its parent at export time."""


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    operation: str | None
    usage_input: int = 0
    usage_output: int = 0
    lineage_broken: bool = False


def capture_context() -> contextvars.Context:
    # Snapshot the live OTel context before crossing a thread/transport boundary.
    return contextvars.copy_context()


def dispatch_tool(fn, *, parent: Span, worker_context: contextvars.Context) -> Span:
    """Run fn inside a worker that re-attaches the captured context.

    The invariant: the tool child span MUST carry the parent's trace_id and a
    resolvable parent_span_id, and the parent MUST carry gen_ai.operation.name.
    """
    if parent.operation is None:
        raise UsageLineageError(
            f"parent span {parent.span_id} lacks gen_ai.operation.name; "
            "cannot establish usage lineage for tool child"
        )

    # Simulate the child span the tool body would create.
    child = Span(
        trace_id=parent.trace_id,
        span_id="child-1",
        parent_span_id=parent.span_id,
        operation="execute_tool",
        usage_input=612,
        usage_output=88,
    )

    # Guardrail: verify lineage before export, not after trace assembly.
    if not child.parent_span_id or child.trace_id != parent.trace_id:
        child.lineage_broken = True
        raise UsageLineageError(
            f"usage-bearing span {child.span_id} orphaned: "
            f"parent={child.parent_span_id!r} trace={child.trace_id!r} "
            f"!= parent trace {parent.trace_id!r}"
        )
    return child


def rollup_usage(spans: list[Span]) -> dict[str, int]:
    """Aggregate only over spans with proven lineage; quarantine the rest."""
    total_in = total_out = 0
    for s in spans:
        if s.lineage_broken:
            continue  # excluded from aggregate, surfaced separately
        total_in += s.usage_input
        total_out += s.usage_output
    return {"input": total_in, "output": total_out}


if __name__ == "__main__":
    root = Span(trace_id="t-1", span_id="root", parent_span_id=None,
                operation="invoke_agent", usage_input=1840)
    # Correct dispatch: context captured and re-attached.
    ctx = capture_context()
    child = dispatch_tool(lambda: None, parent=root, worker_context=ctx)
    print(rollup_usage([root, child]))  # {'input': 2452, 'output': 88}

    # Broken dispatch: parent lost its operation attribute (e.g. re-parented root).
    orphan_parent = Span(trace_id="t-2", span_id="p2", parent_span_id=None,
                         operation=None, usage_input=1840)
    try:
        dispatch_tool(lambda: None, parent=orphan_parent, worker_context=ctx)
    except UsageLineageError as e:
        print(f"quarantined: {e}")
