# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-parent-span-link-across-an-agent-handoff-causal-trace-replay-divergence-from-genai-span-link-aliasing-under-ret.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-parent-span-link-across-an-agent-handoff-causal-trace-replay-divergence-from-genai-span-link-aliasing-under-ret.warrant.json
# Markdown SHA-256:   6c04d27aafe512914068e0261b442986abbb29a4fa803ecd2769c9239dea3261
# Code AST SHA-256:   ce58a8d7d3c4fa258cde1e44b51d5b2255943a37e123cdfab68c25d36a7b673f
# Verified Classes:   CausalAliasingError, SpanRecord, AttemptRegistry
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class CausalAliasingError(RuntimeError):
    """Raised when a downstream agent invocation would create a duplicate
    parent-child causal edge to the same dispatcher within one conversation,
    corrupting replay determinism."""
    pass


@dataclass
class SpanRecord:
    span_id: str
    name: str
    parent_span_id: Optional[str]
    links: list = field(default_factory=list)


class AttemptRegistry:
    """Tracks attempt tokens per conversation to enforce the invariant:
    at most one parent edge per (dispatcher, downstream_agent, conversation)."""

    def __init__(self):
        # conversation_id -> set of attempt tokens already seen
        self._seen: dict[str, set[str]] = {}

    @staticmethod
    def attempt_token(conversation_id: str, dispatcher_span_id: str,
                      downstream_agent_id: str, logical_seq: int) -> str:
        raw = f"{conversation_id}|{dispatcher_span_id}|{downstream_agent_id}|{logical_seq}"
        return hashlib.sha256(raw.encode()).hexdigest()[:16]

    def claim(self, conversation_id: str, token: str) -> bool:
        """Atomically claim an attempt token. Returns True if first attempt."""
        bucket = self._seen.setdefault(conversation_id, set())
        if token in bucket:
            return False
        bucket.add(token)
        return True


def emit_invoke_agent_span(
    registry: AttemptRegistry,
    conversation_id: str,
    dispatcher_span_id: str,
    downstream_agent_id: str,
    logical_seq: int,
    new_span_id: str,
    previous_attempt_span_id: Optional[str] = None,
    attempt_group_span_id: Optional[str] = None,
) -> SpanRecord:
    token = registry.attempt_token(
        conversation_id, dispatcher_span_id, downstream_agent_id, logical_seq
    )
    is_first = registry.claim(conversation_id, token)

    if is_first:
        # First attempt: parent edge to dispatcher is permitted.
        return SpanRecord(
            span_id=new_span_id,
            name=f"invoke_agent {downstream_agent_id}",
            parent_span_id=dispatcher_span_id,
            links=[],
        )

    # Retry / resume: MUST NOT parent to dispatcher. Link instead.
    if previous_attempt_span_id is None:
        raise CausalAliasingError(
            f"Retry of {downstream_agent_id} in conversation {conversation_id} "
            f"has no previous_attempt_span_id; cannot emit retry_of link. "
            f"Refusing to emit parent edge to dispatcher {dispatcher_span_id} "
            f"as this would alias causal lineage and break replay."
        )

    parent = attempt_group_span_id  # may be None -> root of attempt group
    return SpanRecord(
        span_id=new_span_id,
        name=f"invoke_agent {downstream_agent_id}",
        parent_span_id=parent,
        links=[{
            "target_span_id": previous_attempt_span_id,
            "kind": "retry_of",
            "attrs": {"attempt_token": token, "attempt_index": logical_seq},
        }],
    )
