# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-of-an-agent-delegation-chain-loses-its-parent-span-link-orphaned-genai-semantic-convention-spans-at-the-second-level-del.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-of-an-agent-delegation-chain-loses-its-parent-span-link-orphaned-genai-semantic-convention-spans-at-the-second-level-del.warrant.json
# Markdown SHA-256:   b097a34afee5df8d2bc85f95f7de7ec31fd319741d0b917ac626d6faf7f48552
# Code AST SHA-256:   7b769250d31b43e4011acf6094b5f1a592dae65bb0fb5ca4ddf61399f04d2bba
# Verified Classes:   OrphanedDelegationSpanError, SpanRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class OrphanedDelegationSpanError(RuntimeError):
    """Raised when a gen_ai delegation span has neither a resolvable parent
    within its trace nor an explicit SpanLink to its delegating span."""


@dataclass
class SpanRecord:
    span_id: str
    trace_id: str
    parent_span_id: Optional[str]
    delegation_depth: int
    delegating_span_id: Optional[str] = None  # from explicit SpanLink
    attributes: dict = field(default_factory=dict)


def validate_delegation_linkage(spans: list[SpanRecord]) -> None:
    """Enforce: every span at delegation depth >= 2 must have either a parent
    in the same trace or an explicit link to its delegating span."""
    by_id = {s.span_id: s for s in spans}
    for span in spans:
        if span.delegation_depth < 2:
            continue
        parent_resolves = (
            span.parent_span_id is not None
            and span.parent_span_id in by_id
            and by_id[span.parent_span_id].trace_id == span.trace_id
        )
        link_resolves = (
            span.delegating_span_id is not None
            and span.delegating_span_id in by_id
            and by_id[span.delegating_span_id].trace_id == span.trace_id
        )
        if not (parent_resolves or link_resolves):
            raise OrphanedDelegationSpanError(
                f"span {span.span_id} (trace {span.trace_id}, depth "
                f"{span.delegation_depth}) has no resolvable parent "
                f"(parent_span_id={span.parent_span_id!r}) and no resolvable "
                f"delegating SpanLink (delegating_span_id="
                f"{span.delegating_span_id!r}); causal graph is broken"
            )


def emit_delegation_span(
    *,
    span_id: str,
    trace_id: str,
    parent_span_id: Optional[str],
    delegation_depth: int,
    delegating_span_id: Optional[str],
) -> SpanRecord:
    record = SpanRecord(
        span_id=span_id,
        trace_id=trace_id,
        parent_span_id=parent_span_id,
        delegation_depth=delegation_depth,
        delegating_span_id=delegating_span_id,
    )
    # Validate this span against the invariant before it leaves the process.
    validate_delegation_linkage([record])
    return record
