# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-parentage-when-a-delegated-subagent-re-emits-a-retried-span-under-a-new-trace-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-parentage-when-a-delegated-subagent-re-emits-a-retried-span-under-a-new-trace-identity.warrant.json
# Markdown SHA-256:   03fe1651cb46c4aa88c30050b808fc2d4b78de37e8fad8dfeadb727d9a321cfe
# Code AST SHA-256:   be664ea6922d9a30892d03ed08be4035767ce82791d1b8475722ccbb10a6342b
# Verified Classes:   OrphanedDelegationSpan, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class OrphanedDelegationSpan(RuntimeError):
    """Raised when a delegated subagent span references an absent parent
    span and carries no retry-invariant correlation token to re-parent it."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    name: str
    delegation_id: Optional[str] = None
    status: str = "OK"
    attributes: dict = field(default_factory=dict)


def inject_context_at_send(current_span: Span, headers: dict) -> dict:
    """Must be called inside the retry loop, after the new attempt span is
    opened. Caching this result across attempts is the root-cause bug."""
    headers = dict(headers)
    headers["traceparent"] = (
        f"00-{current_span.trace_id}-{current_span.span_id}-01"
    )
    return headers


def validate_trajectory(spans: list[Span]) -> None:
    """Fail-closed check: every span's parent must be present, unless the
    span carries a delegation_id that permits deterministic re-parenting."""
    present = {s.span_id for s in spans}
    for s in spans:
        if s.parent_span_id is None:
            continue  # trace root
        if s.parent_span_id not in present:
            if s.delegation_id is None:
                raise OrphanedDelegationSpan(
                    f"span {s.span_id} ({s.name}) references absent parent "
                    f"{s.parent_span_id} in trace {s.trace_id} and has no "
                    f"delegation_id for re-parenting; trajectory untrustworthy"
                )
            # Re-parentable: reconciler will re-link via delegation_id.
            s.attributes["reparent_pending"] = s.delegation_id


def simulate_retry_without_reinjection() -> None:
    trace = "T"
    # Attempt 1: delegation span A1, subagent caches header, times out.
    a1 = Span(trace, "A1", None, "delegate", status="ERROR")
    stale_headers = inject_context_at_send(a1, {})  # captured at construction
    # Attempt 2: orchestrator mints A2 but re-sends the STALE cached header.
    a2 = Span(trace, "A2", None, "delegate", status="OK")
    # Subagent emits child against stale A1 (now evicted by tail sampler).
    child = Span(trace, "C1", parent_span_id="A1", name="subagent.retrieve")
    # A1 dropped from retained trace; only A2 + C1 survive.
    validate_trajectory([a2, child])  # raises


if __name__ == "__main__":
    simulate_retry_without_reinjection()
