# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconstruct-a-causal-trace-across-a-multi-agent-failure-when-opentelemetry-span-links-collapse-under-fan-in.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconstruct-a-causal-trace-across-a-multi-agent-failure-when-opentelemetry-span-links-collapse-under-fan-in.warrant.json
# Markdown SHA-256:   214918e817f1491315ba9a5020b624cbd3f79e856f227a5c649c4f40cf7232a6
# Code AST SHA-256:   c5191469a72b0dce853a8239065b370eb0b9725829543731609baa6d77f5dd18
# Verified Classes:   CausalReconstructionError, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalReconstructionError(RuntimeError):
    """Raised when a span-link graph cannot be reduced to a justified causal order."""


@dataclass
class Span:
    span_id: str
    instance_id: str
    seq: int
    start_ns: int
    links: list[dict] = field(default_factory=list)  # each: {"target": span_id, "role": str}
    attributes: dict = field(default_factory=dict)


VALID_ROLES = {"spawned", "awaited", "joined", "shared_resource"}


def reconstruct_order(spans: list[Span]) -> list[str]:
    """
    Reconstruct a causal order from role-annotated links + per-instance seq.
    Refuses to fall back to timestamps across process boundaries.
    """
    by_id = {s.span_id: s for s in spans}

    # Guard 1: every link must be role-annotated.
    for s in spans:
        for link in s.links:
            role = link.get("role")
            if role not in VALID_ROLES:
                raise CausalReconstructionError(
                    f"span {s.span_id} has unannotated link to {link.get('target')!r}; "
                    f"refusing to infer causal edge from bare association"
                )

    # Guard 2: only 'spawned'/'awaited' links create directed causal edges.
    # 'shared_resource' and 'joined' are associations, not causation.
    edges: dict[str, set[str]] = {s.span_id: set() for s in spans}
    for s in spans:
        for link in s.links:
            if link["role"] in ("spawned", "awaited"):
                src, dst = s.span_id, link["target"]
                if dst not in by_id:
                    raise CausalReconstructionError(
                        f"span {src} links to unknown span {dst}"
                    )
                edges[src].add(dst)

    # Guard 3: per-instance seq must be strictly increasing along any edge
    # that stays within one instance; cross-instance edges are allowed but
    # must not require a timestamp tiebreak.
    for src, dsts in edges.items():
        for dst in dsts:
            a, b = by_id[src], by_id[dst]
            if a.instance_id == b.instance_id and a.seq >= b.seq:
                raise CausalReconstructionError(
                    f"causal edge {src}->{dst} violates local seq "
                    f"({a.seq} >= {b.seq}) within instance {a.instance_id}"
                )

    # Kahn's algorithm; detect non-unique order rather than tiebreaking.
    indeg = {sid: 0 for sid in edges}
    for src, dsts in edges.items():
        for dst in dsts:
            indeg[dst] += 1

    ready = [sid for sid, d in indeg.items() if d == 0]
    order: list[str] = []
    while ready:
        if len(ready) > 1:
            raise CausalReconstructionError(
                f"ambiguous causal order: {len(ready)} spans simultaneously "
                f"ready ({sorted(ready)}); refusing to break tie by timestamp"
            )
        cur = ready.pop()
        order.append(cur)
        for dst in edges[cur]:
            indeg[dst] -= 1
            if indeg[dst] == 0:
                ready.append(dst)

    if len(order) != len(edges):
        raise CausalReconstructionError(
            "causal graph contains a cycle; link roles contradict sequence constraints"
        )
    return order
