# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-semantic-convention-span-links-when-a-delegated-sub-agent-re-emits-a-parent-span-id-under-a-fresh-trace-context.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-semantic-convention-span-links-when-a-delegated-sub-agent-re-emits-a-parent-span-id-under-a-fresh-trace-context.warrant.json
# Markdown SHA-256:   c893323327534c3b030d6108c694ac57cb1c520a7494f404b7fb1a2034a4a574
# Code AST SHA-256:   82bf9f35b79b075cf7cc73895ef9439b44aa6fc50ab6d42f22c7997e6ac521ff
# Verified Classes:   SpanLinkInvariantViolation, SpanRef
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SpanLinkInvariantViolation(RuntimeError):
    """Raised when a delegated span's link cannot be soundly resolved."""


@dataclass(frozen=True)
class SpanRef:
    trace_id: str
    span_id: str

    def is_same_trace(self, other: "SpanRef") -> bool:
        return self.trace_id == other.trace_id


def emit_delegated_span(
    child: SpanRef,
    link: SpanRef,
    backend_indexes_by_composite_key: bool,
) -> SpanRef:
    """Validate and, if needed, repair the link on a delegated sub-agent span.

    Returns the (possibly repaired) link to persist. Raises if the link is
    unresolvable and must not be written.
    """
    if not backend_indexes_by_composite_key:
        raise SpanLinkInvariantViolation(
            f"backend resolves links by span_id alone; link {link} is unsound "
            "for cross-trace causality and must not be persisted"
        )

    if link.trace_id == child.trace_id and link.span_id == child.span_id:
        # Child never left the parent context: this should have been a
        # parent-child span, not a link. A self-link is a hard error.
        raise SpanLinkInvariantViolation(
            f"self-referential span link: child {child} links to itself; "
            "delegation did not cross a trace boundary"
        )

    if link.span_id == child.span_id and not link.is_same_trace(child):
        # Child inherited the caller's span_id as its own identity.
        # Repair: regenerate child identity, keep the link as the caller's pair.
        repaired_child = SpanRef(trace_id=child.trace_id, span_id=_fresh_span_id())
        # Caller is responsible for emitting repaired_child with
        # gen_ai.delegation.repaired=true; we return the corrected link.
        return SpanRef(trace_id=link.trace_id, span_id=link.span_id)

    return link


def _fresh_span_id() -> str:
    import secrets
    return secrets.token_hex(8)
