# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-tool-spans-when-the-trace-collector-truncates-parent-agent-span-ids-mid-incident.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-tool-spans-when-the-trace-collector-truncates-parent-agent-span-ids-mid-incident.warrant.json
# Markdown SHA-256:   9f1dc4be5709a35aa68b80014d85e617b28f82de95214370d514412e014f4d01
# Code AST SHA-256:   383d58213f0c9fa7090de0755f2e68d78f25b08b5f33659a3e298a4d7d5cd896
# Verified Classes:   TraceCorrelationError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TraceCorrelationError(RuntimeError):
    """Raised when a span's resolved causal parent disagrees with its native parent."""
    pass


@dataclass
class Span:
    span_id: str
    native_parent_span_id: str | None
    causal_chain_display: str | None  # advisory only, may be truncated


def resolve_authoritative_parent(span: Span, known_span_ids: set[str]) -> str | None:
    """
    Resolve the parent edge for forensic reconstruction.

    The native parentSpanId is the single source of truth. The display-only
    causal chain is never used to infer a parent; if it disagrees, that is a
    correlation-integrity signal, not a join hint.
    """
    native = span.native_parent_span_id

    # Root span: no parent, must have no misleading chain claim.
    if native is None:
        if span.causal_chain_display:
            raise TraceCorrelationError(
                f"span {span.span_id} has no native parent but carries a "
                f"display chain '{span.causal_chain_display}'"
            )
        return None

    # Native parent must resolve to a known span in the trace, else orphan.
    if native not in known_span_ids:
        raise TraceCorrelationError(
            f"span {span.span_id} references unknown native parent {native}; "
            f"treat as orphan, do not infer from display chain"
        )

    # Cross-check the advisory display chain against the native edge.
    if span.causal_chain_display:
        segments = span.causal_chain_display.rstrip(".").split(".")
        display_parent = segments[-2] if len(segments) >= 2 else None
        if display_parent is not None and display_parent != native:
            raise TraceCorrelationError(
                f"span {span.span_id}: display chain implies parent "
                f"{display_parent!r} but native parent is {native!r}; "
                f"likely attribute truncation—quarantine trace"
            )

    return native


def build_causal_chain(spans: list[Span]) -> dict[str, list[str]]:
    """Rebuild agent->model->tool chains using only authoritative edges."""
    known = {s.span_id for s in spans}
    children: dict[str, list[str]] = {}
    for s in spans:
        parent = resolve_authoritative_parent(s, known)
        if parent is not None:
            children.setdefault(parent, []).append(s.span_id)
    return children
