# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-propagate-rather-than-regenerate-the-parent-span-id-across-a-nested-multi-agent-handoff-retry.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-propagate-rather-than-regenerate-the-parent-span-id-across-a-nested-multi-agent-handoff-retry.warrant.json
# Markdown SHA-256:   d25e1fc38e487f347ec42a4e36d207ba7cb83448451aa9d5da7b3f58e7677238
# Code AST SHA-256:   974ffe8242588e6ce0573d86591e1657c9d05a0e19b7b455156c7b7ff221659c
# Verified Classes:   SpanPropagationError, RetryEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SpanPropagationError(RuntimeError):
    """Raised when a nested handoff retry would regenerate a parent span ID
    instead of propagating the original attempt's span identity."""
    pass


@dataclass(frozen=True)
class RetryEnvelope:
    trace_id: str
    parent_span_id: str
    # The span ID minted for THIS logical attempt by the owning caller.
    attempt_span_id: Optional[str]
    attempt_number: int
    inputs_hash: str


def resolve_child_span_id(envelope: RetryEnvelope, *, is_retry: bool,
                          callee_generated_id: Optional[str]) -> str:
    """Decide the span ID a callee must adopt for a nested handoff.

    Invariant: a retry of the same logical attempt reuses attempt_span_id;
    it must never adopt a freshly generated ID.
    """
    if not is_retry:
        if envelope.attempt_span_id is None:
            raise SpanPropagationError(
                "first delivery of handoff requires a caller-minted attempt_span_id; "
                "callee must not mint its own"
            )
        return envelope.attempt_span_id

    # Retry path.
    if envelope.attempt_span_id is None:
        raise SpanPropagationError(
            f"retry #{envelope.attempt_number} for inputs_hash={envelope.inputs_hash} "
            "arrived without the original attempt_span_id; propagating is impossible "
            "and regenerating would fork the trace"
        )
    if callee_generated_id is not None and callee_generated_id != envelope.attempt_span_id:
        raise SpanPropagationError(
            f"callee generated span_id={callee_generated_id} on retry but envelope "
            f"carries attempt_span_id={envelope.attempt_span_id}; refusing to fork "
            "logical attempt into sibling spans"
        )
    return envelope.attempt_span_id
