# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-emit-a-distinct-span-link-instead-of-a-parent-child-edge-in-genai-multi-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-emit-a-distinct-span-link-instead-of-a-parent-child-edge-in-genai-multi-agent-traces.warrant.json
# Markdown SHA-256:   41bb5d19bceeea1a9a5d76a2694e18ff3f4e4598f29502e63a2aa8e3a7ba7eae
# Code AST SHA-256:   3914d4c6313ad320ad7133cd5b9c596e860763470f9624f3fa082396eb63d277
# Verified Classes:   SpanCausalityError, SpanRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SpanCausalityError(RuntimeError):
    """Raised when a span is about to be encoded with an invalid causal edge."""
    pass


@dataclass
class SpanRecord:
    span_id: str
    parent_id: str | None
    start_time: float
    end_time: float
    operation: str


def encode_causal_edge(
    producer: SpanRecord,
    consumer: SpanRecord,
    *,
    reused: bool,
    concurrent_predecessors: int,
    skew_tolerance: float = 0.005,
) -> str:
    """
    Decide whether consumer should parent under producer or link to it.
    Returns 'child' or 'link'. Raises SpanCausalityError on an
    unrepresentable relation that must not be silently coerced.
    """
    contained = (
        consumer.start_time >= producer.start_time - skew_tolerance
        and consumer.end_time <= producer.end_time + skew_tolerance
    )

    # Reuse or fan-in: containment is irrelevant, causality must be a link.
    if reused or concurrent_predecessors > 1:
        return "link"

    if not contained:
        # Consumer outlives or predates producer: a parent edge would
        # invert timestamps and corrupt critical-path analysis.
        raise SpanCausalityError(
            f"span {consumer.span_id} ({consumer.operation}) is not temporally "
            f"contained by {producer.span_id} ({producer.operation}); "
            f"encode as a link with caused_by, not a parent-child edge"
        )

    return "child"
