# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-parent-span-link-when-genai-semantic-convention-trace-context-is-propagated-across-a-multi-agent-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-parent-span-link-when-genai-semantic-convention-trace-context-is-propagated-across-a-multi-agent-handoff.warrant.json
# Markdown SHA-256:   69a1d0a669b3103f91a958e9ac51921da4fc218943138b35bc2597c0460887c2
# Code AST SHA-256:   ed4324eaec57b73abf27932d47253a4a2efb7ae9cd6347d888281ac655c5d5ce
# Verified Classes:   StaleParentContextError, Span
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleParentContextError(RuntimeError):
    """Raised when a child span's parent link is causally impossible."""


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    trace_id: str
    start_time: float
    end_time: Optional[float]
    conversation_id: str
    request_hash: Optional[str] = None


def resolve_parent_context(
    header_traceparent: Optional[str],
    cached_span_context: Optional[Span],
    inbound_conversation_id: str,
) -> Optional[str]:
    """Return the span-id to parent under, or None for an explicit root.

    Parentage MUST come from the transport header, never from a
    conversation-scoped cache. The cache is consulted only to detect
    re-binding (trace-id mismatch), never to supply a parent span-id.
    """
    if header_traceparent is None:
        if cached_span_context is not None:
            # Fail closed: do not silently inherit a stale parent.
            return None
        return None
    parts = header_traceparent.split("-")
    if len(parts) != 4:
        raise StaleParentContextError(
            f"malformed traceparent for conversation {inbound_conversation_id!r}: "
            f"{header_traceparent!r}"
        )
    trace_id, parent_span_id = parts[1], parts[2]
    if trace_id == "0" * 32 or parent_span_id == "0" * 16:
        raise StaleParentContextError(
            f"zero trace/span id in traceparent for conversation "
            f"{inbound_conversation_id!r}"
        )
    if cached_span_context is not None and cached_span_context.trace_id != trace_id:
        # Conversation re-bound; cache is stale. Parent under header.
        return parent_span_id
    return parent_span_id


def validate_lineage(child: Span, parent: Span) -> None:
    """Enforce the causal-window invariant on a claimed parent edge."""
    if child.parent_span_id != parent.span_id:
        raise StaleParentContextError(
            f"span {child.span_id} claims parent {child.parent_span_id}, "
            f"but validator was given {parent.span_id}"
        )
    if child.start_time < parent.start_time:
        raise StaleParentContextError(
            f"span {child.span_id} starts before parent {parent.span_id} "
            f"({child.start_time} < {parent.start_time})"
        )
    if parent.end_time is not None and child.start_time > parent.end_time:
        raise StaleParentContextError(
            f"span {child.span_id} starts after parent {parent.span_id} ended "
            f"({child.start_time} > {parent.end_time}); stale parent context"
        )
    if (
        parent.request_hash is not None
        and child.request_hash is not None
        and parent.request_hash != child.request_hash
    ):
        raise StaleParentContextError(
            f"request-hash mismatch on edge {parent.span_id}->{child.span_id}: "
            f"{parent.request_hash} != {child.request_hash}"
        )
