# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-parent-child-span-link-as-authoritative-when-reconstructing-a-multi-agent-causal-chain-and-when-must-it.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-parent-child-span-link-as-authoritative-when-reconstructing-a-multi-agent-causal-chain-and-when-must-it.warrant.json
# Markdown SHA-256:   010a897bfd2a4dc8446314fe352581b7b4579b809763f958bfde873e41922a7b
# Code AST SHA-256:   8d3e40924b87c2666cc2ad9eb0136b50cfa3622b03f747bb0e9dc90b755dfec4
# Verified Classes:   CausalityReconstructionError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class CausalityReconstructionError(RuntimeError):
    """Raised when a declared span link cannot be trusted for causal reconstruction."""
    pass


def validate_parent_edge(child: dict, parent: dict, siblings: list[dict]) -> None:
    """
    Enforce the four conditions of validity for a declared parent-child span link.
    Raises CausalityReconstructionError on any violation that makes the edge
    non-authoritative for causal replay.
    """
    # Condition 2: child must not predate parent's end (causality inversion).
    if child["start_time"] < parent["end_time"]:
        raise CausalityReconstructionError(
            f"causality inversion: child {child['span_id']} started "
            f"({child['start_time']}) before parent {parent['span_id']} ended "
            f"({parent['end_time']})"
        )

    # Condition 1: parent must still be open or its end-state recorded at child creation.
    if parent.get("exported_at") is not None and parent["exported_at"] < child["start_time"]:
        raise CausalityReconstructionError(
            f"stale parent: {parent['span_id']} exported at {parent['exported_at']} "
            f"before child {child['span_id']} created at {child['start_time']}"
        )

    # Condition 3: causation token required when siblings share an operation.
    same_op_siblings = [
        s for s in siblings
        if s["span_id"] != child["span_id"]
        and s.get("gen_ai.operation.name") == child.get("gen_ai.operation.name")
    ]
    if same_op_siblings and "gen_ai.agent.handoff.seq" not in child.get("attributes", {}):
        raise CausalityReconstructionError(
            f"ambiguous causality: child {child['span_id']} shares operation "
            f"{child.get('gen_ai.operation.name')} with {len(same_op_siblings)} "
            f"sibling(s) but carries no handoff.seq token; ordering cannot be asserted"
        )

    # Condition 4: trace_id must match across the edge.
    if child["trace_id"] != parent["trace_id"]:
        raise CausalityReconstructionError(
            f"trace_id mutation across handoff: child {child['trace_id']} != "
            f"parent {parent['trace_id']}"
        )


def reconstruct_chain(spans: list[dict]) -> list[dict]:
    """Reconstruct causal chain, validating every declared edge."""
    by_id = {s["span_id"]: s for s in spans}
    children: dict[str, list[dict]] = {}
    for s in spans:
        pid = s.get("parent_span_id")
        if pid:
            children.setdefault(pid, []).append(s)

    edges = []
    for pid, kids in children.items():
        parent = by_id.get(pid)
        if parent is None:
            raise CausalityReconstructionError(
                f"orphaned subtree: parent {pid} not present in trace"
            )
        for kid in kids:
            validate_parent_edge(kid, parent, kids)
            edges.append((pid, kid["span_id"]))
    return edges
