# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-a-causal-span-orphaned-parent-links-under-cross-agent-context-propagation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-a-causal-span-orphaned-parent-links-under-cross-agent-context-propagation.warrant.json
# Markdown SHA-256:   45560fda75f5cd13df11951a88ac2ab3ca5fec4b21f7a4ab331afaea1d9b51f4
# Code AST SHA-256:   9e0f3196e703bd7b7d2fc83c27d6a4e2168661f912287067ded9decf417b1a0e
# Verified Classes:   OrphanedParentError, SpanContext, ChildSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class OrphanedParentError(RuntimeError):
    """Raised when a span cannot be causally linked to its declared parent."""
    pass


@dataclass
class SpanContext:
    trace_id: str
    span_id: str
    start_time: float
    end_time: Optional[float] = None


@dataclass
class ChildSpan:
    trace_id: str
    span_id: str
    start_time: float
    end_time: float
    declared_parent: Optional[SpanContext]
    payload_trace_id: Optional[str]  # trace_id embedded in the consumed payload


def close_span_causally(child: ChildSpan, live_envelope_trace_id: str) -> str:
    """
    Decide whether `child` may be closed against its declared parent.
    Returns 'causal' if the edge is attested, 're-rooted' if it must be
    downgraded to a non-causal link. Raises on provable non-causality.
    """
    parent = child.declared_parent

    if parent is None:
        return "re-rooted"  # root span, no claim to verify

    # 1. Temporal inversion is never benign in agent traces -> fail closed.
    if child.start_time < parent.start_time or child.end_time < parent.start_time:
        raise OrphanedParentError(
            f"temporal inversion: child {child.span_id} "
            f"(start={child.start_time:.3f}) precedes parent {parent.span_id} "
            f"(start={parent.start_time:.3f}); context token minted out of order "
            f"(retry re-root or fan-out join reuse)"
        )

    # 2. Liveness: parent must have been durably closed.
    if parent.end_time is None:
        raise OrphanedParentError(
            f"dead parent: {parent.span_id} never closed; "
            f"child {child.span_id} inherited an abandoned attempt's context"
        )

    # 3. Lineage: payload's embedded trace must match the live envelope.
    if child.payload_trace_id is not None and child.payload_trace_id != live_envelope_trace_id:
        raise OrphanedParentError(
            f"cross-trace transplant: payload trace {child.payload_trace_id} "
            f"!= live envelope {live_envelope_trace_id}; "
            f"child {child.span_id} adopted cached/foreign parent {parent.span_id}"
        )

    # 4. Lineage identity between declared parent and child trace.
    if parent.trace_id != child.trace_id:
        return "re-rooted"  # unverified, preserve as link, do not fabricate edge

    return "causal"


def emit_child_span(child: ChildSpan, live_envelope_trace_id: str) -> dict:
    verdict = close_span_causally(child, live_envelope_trace_id)
    if verdict == "causal":
        return {"span_id": child.span_id, "parent_span_id": child.declared_parent.span_id,
                "edge": "causal"}
    # re-rooted: mint a local parent recording the true production event
    return {"span_id": child.span_id,
            "parent_span_id": f"local:{child.span_id}:producer",
            "edge": "causal",
            "links": [{"to": child.declared_parent.span_id if child.declared_parent else None,
                       "causality": "unverified"}]}
