# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-emit-a-parent-span-when-the-handoff-graph-s-causal-parent-is-itself-a-late-arriving-peer.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-emit-a-parent-span-when-the-handoff-graph-s-causal-parent-is-itself-a-late-arriving-peer.warrant.json
# Markdown SHA-256:   cd50b5968c31b13b8d91530451eceae28dd114c807adabb4236bcee12626db47
# Code AST SHA-256:   f4b145e04b84d3650b2d5728c9462cb0f8a80df77f6dd808f8497ec9249b2b77
# Verified Classes:   CausalParentUnresolvable, SpanIdCollision, CausalToken, EmittedSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalParentUnresolvable(RuntimeError):
    """Raised when a child span cannot be soundly parented to a remote causal token."""


class SpanIdCollision(RuntimeError):
    """Raised when a resumed instance would re-emit an already-used span_id."""


@dataclass(frozen=True)
class CausalToken:
    trace_id: str
    span_id: str
    generation: int
    signature_valid: bool
    export_acked: bool
    export_deadline: float  # monotonic seconds
    retracted: bool


@dataclass(frozen=True)
class EmittedSpan:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    parent_status: Optional[str]  # "unresolved" | "retracted" | None
    link_span_id: Optional[str]
    link_generation: Optional[int]
    resumed_from_span_id: Optional[str]


def emit_child_span(
    *,
    trace_id: str,
    new_span_id: str,
    token: Optional[CausalToken],
    max_observed_generation: int,
    now: float,
    previously_emitted_span_ids: set[str],
) -> EmittedSpan:
    if new_span_id in previously_emitted_span_ids:
        raise SpanIdCollision(
            f"span_id {new_span_id!r} already emitted in trace {trace_id!r}; "
            "collector dedup will silently drop this subtree. Mint a fresh span_id "
            "and set resumed_from_span_id instead."
        )

    if token is None:
        # No causal claim at all: local root, no parent, no link.
        return EmittedSpan(
            trace_id=trace_id,
            span_id=new_span_id,
            parent_span_id=None,
            parent_status=None,
            link_span_id=None,
            link_generation=None,
            resumed_from_span_id=None,
        )

    if token.trace_id != trace_id:
        raise CausalParentUnresolvable(
            f"token trace_id {token.trace_id!r} does not match emitting trace {trace_id!r}"
        )

    resolvable = (
        token.signature_valid
        and token.generation == max_observed_generation
        and not token.retracted
        and (token.export_acked or now < token.export_deadline)
    )

    if resolvable:
        return EmittedSpan(
            trace_id=trace_id,
            span_id=new_span_id,
            parent_span_id=token.span_id,
            parent_status=None,
            link_span_id=None,
            link_generation=None,
            resumed_from_span_id=None,
        )

    if token.retracted:
        raise CausalParentUnresolvable(
            f"causal token for span {token.span_id!r} gen {token.generation} was retracted; "
            "emit unresolved-with-link and let the resolution protocol mark it retracted, "
            "do not re-parent to a newer generation"
        )

    # Unresolved but linked: preserve the causal claim without asserting a parent.
    return EmittedSpan(
        trace_id=trace_id,
        span_id=new_span_id,
        parent_span_id=None,
        parent_status="unresolved",
        link_span_id=token.span_id,
        link_generation=token.generation,
        resumed_from_span_id=None,
    )
