# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-causal-trace-as-un-joinable-when-a-sub-agent-re-emits-an-inherited-span-id-under-a-fresh-trace-context.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-causal-trace-as-un-joinable-when-a-sub-agent-re-emits-an-inherited-span-id-under-a-fresh-trace-context.warrant.json
# Markdown SHA-256:   03cd208c6052f9537bcf474dc41845aebb248e53ffabb083200765ce745fc1de
# Code AST SHA-256:   7c9731ced94014de5e5a85c9d3e6082f8ff153f44e6b1f2be9008579d4bece6e
# Verified Classes:   UnjoinableTraceError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class UnjoinableTraceError(RuntimeError):
    """Raised when causal reconstruction hits an edge that cannot be validly joined."""


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None


def join_edge(child: Span, parent: Span | None, *, candidates: int) -> None:
    if child.parent_span_id is None:
        return
    if candidates > 1:
        raise UnjoinableTraceError(
            f"ambiguous parentage: span_id={child.parent_span_id} resolves to "
            f"{candidates} spans; lineage quarantined"
        )
    if parent is None:
        raise UnjoinableTraceError(
            f"dangling parent: {child.parent_span_id} not found for span {child.span_id}"
        )
    if child.trace_id != parent.trace_id:
        raise UnjoinableTraceError(
            f"cross-trace parent edge: child {child.span_id} in {child.trace_id} "
            f"claims parent {parent.span_id} in {parent.trace_id}; "
            f"demote to Link, do not join"
        )


def reconstruct(spans: list[Span]) -> dict[str, list[str]]:
    by_id: dict[str, list[Span]] = {}
    for s in spans:
        by_id.setdefault(s.span_id, []).append(s)
    tree: dict[str, list[str]] = {}
    for child in spans:
        if child.parent_span_id is None:
            tree.setdefault(child.trace_id, []).append(child.span_id)
            continue
        cands = by_id.get(child.parent_span_id, [])
        parent = cands[0] if len(cands) == 1 else None
        join_edge(child, parent, candidates=len(cands))
        tree.setdefault(child.trace_id, []).append(child.span_id)
    return tree
