# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-lineage-collapse-in-opentelemetry-genai-span-attributes-when-an-agent-re-emits-a-tool-call-under-a-new-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-lineage-collapse-in-opentelemetry-genai-span-attributes-when-an-agent-re-emits-a-tool-call-under-a-new-trace.warrant.json
# Markdown SHA-256:   7cbc0d2056a724f9f56b8710d390443a27b52de45c68bd5bf47aad96a985ae50
# Code AST SHA-256:   b14be97068e73121c95ee8ea818321006f6fc0647430a1ddb079e1982baead68
# Verified Classes:   LineageCollapseError, GenAISpanView
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class LineageCollapseError(RuntimeError):
    """Raised when a re-issued tool call loses its causal edge to the failed attempt."""
    pass


@dataclass
class GenAISpanView:
    trace_id: str
    span_id: str
    operation_name: str          # gen_ai.operation.name
    tool_name: Optional[str]     # gen_ai.tool.name
    tool_call_id: Optional[str]  # gen_ai.tool.call.id
    input_tokens: Optional[int]  # gen_ai.usage.input_tokens
    status: str                  # "OK" | "ERROR"
    linked_span_ids: tuple = ()  # SpanLink targets
    start_ns: int = 0


def assert_lineage_preserved(
    failed: GenAISpanView,
    retry_root: GenAISpanView,
    *,
    token_parity_tolerance: int = 16,
    max_gap_ns: int = 60_000_000_000,
) -> None:
    if failed.operation_name != "execute_tool" or retry_root.operation_name != "invoke_agent":
        raise LineageCollapseError(
            f"unexpected span roles: failed={failed.operation_name}, retry={retry_root.operation_name}"
        )

    # 1. Explicit SpanLink preserves the edge across a trace split.
    if failed.span_id in retry_root.linked_span_ids:
        return

    # 2. Token parity implies an independent attempt, not a resumed continuation.
    if (
        failed.input_tokens is not None
        and retry_root.input_tokens is not None
        and abs(retry_root.input_tokens - failed.input_tokens) <= token_parity_tolerance
    ):
        return

    # 3. Conjunctive collapse signature.
    same_tool = retry_root.tool_name == failed.tool_name
    missing_call_id = failed.tool_call_id is None
    within_window = 0 <= (retry_root.start_ns - failed.start_ns) <= max_gap_ns

    if same_tool and missing_call_id and within_window:
        raise LineageCollapseError(
            "re-issued tool call lost lineage: "
            f"tool={failed.tool_name!r}, failed_span={failed.span_id}, "
            f"retry_trace={retry_root.trace_id}, no SpanLink, "
            f"token delta={retry_root.input_tokens} - {failed.input_tokens}"
        )

    # Fallthrough: not a collapse under our predicate; log-worthy but not fatal.
    return


def emit_retry_span(runtime, failed: GenAISpanView, retry_root: GenAISpanView) -> None:
    """Wraps span emission so a collapsed lineage fails closed at export time."""
    try:
        assert_lineage_preserved(failed, retry_root)
    except LineageCollapseError:
        # Fail closed: refuse to export a retry span that breaks the invariant
        # until the runtime attaches a SpanLink or proves token parity.
        runtime.mark_lineage_degraded(retry_root.trace_id)
        raise
    runtime.export(retry_root)
