# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-parent-child-correlation-when-semantic-convention-span-links-are-resolved-across-a-fan-out-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-parent-child-correlation-when-semantic-convention-span-links-are-resolved-across-a-fan-out-boundary.warrant.json
# Markdown SHA-256:   4405c5066deb2c06edaf21f6fd4bc6eca760c4ed934d2d78c6f70d5df673101d
# Code AST SHA-256:   4741a78a53637a9ad2663eb7fd27d2e1acf26296aae7e6cc8d615d87127d8e6f
# Verified Classes:   CausalLinkAmbiguityError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalLinkAmbiguityError(RuntimeError):
    """Raised when a span's causal parent cannot be resolved to exactly one producer."""


@dataclass
class Span:
    span_id: str
    agent_id: str
    conversation_id: str
    operation_name: str
    delegation_id: Optional[str] = None  # minted by orchestrator at dispatch
    parent_span_id: Optional[str] = None  # structural parent (worker pool)


def resolve_causal_parent(consumer: Span, candidates: list[Span]) -> Span:
    """Resolve the unique causal producer for a consumer span.

    Resolution key MUST be the per-delegation nonce. Ambient attributes
    (conversation_id, operation_name, agent_id) are NOT injective across a
    fan-out and will collapse many-to-one.
    """
    if consumer.delegation_id is None:
        raise CausalLinkAmbiguityError(
            f"span {consumer.span_id} has no delegation_id; "
            f"ambient attrs (conv={consumer.conversation_id}, "
            f"op={consumer.operation_name}) are non-injective under fan-out"
        )

    matches = [
        c for c in candidates
        if c.delegation_id == consumer.delegation_id
        and c.agent_id != consumer.agent_id  # producer is a different agent
    ]

    if len(matches) != 1:
        raise CausalLinkAmbiguityError(
            f"span {consumer.span_id} resolved to {len(matches)} causal parents "
            f"for delegation_id={consumer.delegation_id}; "
            f"expected exactly 1 (fan-out collapse or retry duplicate)"
        )

    return matches[0]


def link_fanout(orchestrator: Span, sub_agents: list[Span], producers: list[Span]) -> dict[str, str]:
    """Link every sub-agent span to its unique causal producer, or fail closed."""
    links: dict[str, str] = {}
    for sub in sub_agents:
        parent = resolve_causal_parent(sub, producers)
        if parent.span_id != orchestrator.span_id:
            raise CausalLinkAmbiguityError(
                f"sub-agent {sub.span_id} linked to {parent.span_id}, "
                f"not orchestrator {orchestrator.span_id}"
            )
        links[sub.span_id] = parent.span_id
    return links
