# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-span-parent-link-across-an-a2a-hop-as-non-authoritative-for-trace-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-span-parent-link-across-an-a2a-hop-as-non-authoritative-for-trace-reconstruction.warrant.json
# Markdown SHA-256:   78896b480620283d2e91d5fb80f75370c3f58ec5ad8ccfb73ddd123ab2172859
# Code AST SHA-256:   5084f984682e867d828cb511068f581b0a0595f688909d25c6fa6e260cff321d
# Verified Classes:   NonAuthoritativeParentLink, Span
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class NonAuthoritativeParentLink(RuntimeError):
    """Raised when a span's parent link fails causal-authority conditions."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    operation: str
    target_agent_id: str
    start_time: float
    end_time: float
    execution_nonce: Optional[str]   # minted into traceparent carrier; None if absent
    replay: bool = False


STITCH_GRACE_SECONDS = 60.0


def assert_authoritative_parent(
    child: Span,
    parent: Optional[Span],
    now: float,
    consumer_does_causal_reasoning: bool,
) -> None:
    """
    Enforce the four authority conditions before allowing a parent link to
    contribute a causal edge to the reconstructed DAG.
    """
    if child.parent_span_id is None:
        return  # genuine root, no claim to verify

    # Condition 1: existence (with stitch grace window for late arrival)
    if parent is None:
        if now - child.end_time < STITCH_GRACE_SECONDS:
            raise NonAuthoritativeParentLink(
                f"span {child.span_id}: parent {child.parent_span_id} not yet "
                f"exported; within stitch grace window. HOLD-AS-UNRESOLVED."
            )
        if consumer_does_causal_reasoning:
            raise NonAuthoritativeParentLink(
                f"span {child.span_id}: parent {child.parent_span_id} never "
                f"exported after grace window; causal consumer must not promote "
                f"to root. HOLD-AS-UNRESOLVED."
            )
        return  # non-causal consumer may promote-to-root

    # Condition 2: temporal precedence
    if parent.end_time > child.start_time and parent.start_time > child.start_time:
        raise NonAuthoritativeParentLink(
            f"span {child.span_id}: parent {parent.span_id} starts after child; "
            f"link is a sequential predecessor, not a concurrent parent."
        )

    # Condition 3: instance identity via execution nonce
    if child.execution_nonce is None or parent.execution_nonce is None:
        if consumer_does_causal_reasoning:
            raise NonAuthoritativeParentLink(
                f"span {child.span_id}: missing execution nonce on carrier; "
                f"cannot distinguish fresh execution from retried carrier. "
                f"HOLD-AS-UNRESOLVED."
            )
    elif child.execution_nonce != parent.execution_nonce:
        raise NonAuthoritativeParentLink(
            f"span {child.span_id}: carrier nonce {child.execution_nonce} != "
            f"parent nonce {parent.execution_nonce}; stale/reused carrier."
        )

    # Condition 4: replay uniqueness is enforced by the caller's fan-out
    # computation; here we only flag that a replay sibling exists.
    if child.replay and consumer_does_causal_reasoning:
        # replay spans are retained for counts but must not add DAG edges
        raise NonAuthoritativeParentLink(
            f"span {child.span_id}: replay artifact; excluded from causal DAG."
        )
