# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-linked-trace-span-parent-span-aliasing-across-agents-under-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-linked-trace-span-parent-span-aliasing-across-agents-under-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   8bd58fe9af82457d7ea604c61937ad38b3000500ea1f78f0ad8895c82c3cc749
# Code AST SHA-256:   f49c32a31c7cf23944081765f5e4464e54ee6bacf06c8da60a3bdacfd04028e2
# Verified Classes:   TraceLinkRejected, SpanRef
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TraceLinkRejected(RuntimeError):
    """Raised when a SpanLink resolves but does not represent the same unit of work."""


@dataclass(frozen=True)
class SpanRef:
    trace_id: str
    span_id: str
    agent_id: str
    conversation_id: str
    run_id: str
    start_time_ns: int


CLOCK_SKEW_TOLERANCE_NS = 5_000_000  # 5 ms


def validate_link(linker: SpanRef, target: SpanRef) -> None:
    """Validate a cross-trace SpanLink before the correlator follows it.

    Raises TraceLinkRejected if the link is an aliasing collision, a
    temporal inversion, or a warrant mismatch. Returns None only when the
    edge is safe to add to the causal graph.
    """
    # 1. Warrant: the target must belong to the same execution run.
    if target.run_id != linker.run_id:
        raise TraceLinkRejected(
            f"run-id mismatch: linker run={linker.run_id!r} "
            f"target run={target.run_id!r}; refusing to join across runs"
        )

    # 2. Temporal monotonicity: target must not start after the linker.
    if target.start_time_ns > linker.start_time_ns + CLOCK_SKEW_TOLERANCE_NS:
        raise TraceLinkRejected(
            f"temporal inversion: target {target.span_id} starts at "
            f"{target.start_time_ns} after linker {linker.span_id} at "
            f"{linker.start_time_ns}; likely replay or aliasing collision"
        )

    # 3. Agent-instance identity: same conversation is a namespace, not a
    #    causal relation. A shared agent_id across distinct instances must
    #    not be treated as the same agent.
    if (
        target.agent_id == linker.agent_id
        and target.conversation_id == linker.conversation_id
        and target.trace_id != linker.trace_id
    ):
        raise TraceLinkRejected(
            f"agent-id aliasing: {target.agent_id!r} in conversation "
            f"{target.conversation_id!r} spans two traces; "
            "mint a per-invocation agent id instead of joining on attributes"
        )


def build_edge(linker: SpanRef, target: SpanRef) -> tuple[str, str]:
    validate_link(linker, target)
    return (linker.span_id, target.span_id)
