# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-opentelemetry-genai-span-as-authoritative-for-cross-agent-causal-ordering-and-when-does-span-modeling.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-opentelemetry-genai-span-as-authoritative-for-cross-agent-causal-ordering-and-when-does-span-modeling.warrant.json
# Markdown SHA-256:   f40de43b4ad8f0f13df47482427096186a260d993f53bd876d820685a3078185
# Code AST SHA-256:   eb0cbd4c336d9e5745950a13abf6d5c855c617df8cc3ba8e3985f5b58b0368aa
# Verified Classes:   CausalGraphInversionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CausalGraphInversionError(RuntimeError):
    """Raised when a GenAI span tree encodes a false causal edge."""
    pass


def validate_handoff_edge(parent_span: dict, child_span: dict) -> None:
    parent_end = parent_span.get("end_time_ns")
    child_start = child_span.get("start_time_ns")

    if parent_end is not None and child_start is not None and parent_end <= child_start:
        raise CausalGraphInversionError(
            f"parent span {parent_span['span_id']} ended at {parent_end}ns "
            f"before child {child_span['span_id']} began at {child_start}ns; "
            f"edge is a context-propagation artifact, not a causal relation"
        )

    if not parent_span.get("gen_ai.agent.handoff", False):
        raise CausalGraphInversionError(
            f"parent span {parent_span['span_id']} is not a handoff span; "
            f"retries of {child_span['span_id']} will appear as concurrent siblings"
        )


def reconstruct_causal_chain(spans: list[dict]) -> list[str]:
    by_id = {s["span_id"]: s for s in spans}
    for child in spans:
        parent_id = child.get("parent_span_id")
        if parent_id is None:
            continue
        parent = by_id.get(parent_id)
        if parent is None:
            raise CausalGraphInversionError(
                f"child {child['span_id']} references missing parent {parent_id}"
            )
        validate_handoff_edge(parent, child)
    return [s["span_id"] for s in spans]
