# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-span-to-trace-correlation-collapse-when-agent-orchestrators-re-parent-llm-spans-across-async-tool-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-span-to-trace-correlation-collapse-when-agent-orchestrators-re-parent-llm-spans-across-async-tool-boundaries.warrant.json
# Markdown SHA-256:   da662c2c481b930f60ce02bd0cf34cb5002e7dc75e16a69a459d70d75d78a4ad
# Code AST SHA-256:   4bc8d92d737ff5b43a668956c1da7dc950cea37cc60dbbc679a497e40f965cab
# Verified Classes:   SpanCorrelationCollapse, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SpanCorrelationCollapse(RuntimeError):
    """Raised when a span's ambient parent contradicts its resource identity."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    agent_id: str                 # from resource attributes, stamped at creation
    ambient_parent_agent_id: Optional[str]  # from execution context at emission
    dispatch_log_parent: Optional[str]      # authoritative, from orchestrator log


def resolve_parent(span: Span, require_dispatch_log: bool = True) -> Optional[str]:
    """
    Decide the parent edge for a span before export.

    Invariant: the parent edge must be justified by data that traveled with
    the work (dispatch log), not by ambient context alone.
    """
    ambient = span.ambient_parent_agent_id
    logged = span.dispatch_log_parent

    if ambient is not None and ambient != span.agent_id:
        # Ambient parent belongs to a different logical agent: the context
        # was re-bound by a reused worker / shared task. Do not trust it.
        if logged is None:
            if require_dispatch_log:
                raise SpanCorrelationCollapse(
                    f"span {span.span_id} (agent={span.agent_id}) has ambient "
                    f"parent agent={ambient} but no dispatch-log record; "
                    f"refusing to emit a parent edge that would invert cost "
                    f"attribution"
                )
            # Degrade to a link, not a parent.
            return None
        return logged

    if logged is not None and logged != span.parent_span_id:
        # Dispatch log disagrees with the serialized parent: the exporter
        # already wrote the wrong edge. Rewrite before export.
        return logged

    return span.parent_span_id


def emit(span: Span) -> Span:
    span.parent_span_id = resolve_parent(span)
    return span
