# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-ordering-of-trace-spans-when-a-federated-agent-hop-injects-its-own-local-clock-into-an-inherited-trace-context.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-ordering-of-trace-spans-when-a-federated-agent-hop-injects-its-own-local-clock-into-an-inherited-trace-context.warrant.json
# Markdown SHA-256:   727516b47f04fdd14c921f03f45eec9daca8b2eac2349cae2e29d8c21b7e7eec
# Code AST SHA-256:   84e26461b7ce1793c6ee77e751c1f3af667ff57820faa0d9928d31c196ab1314
# Verified Classes:   CausalOrderViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CausalOrderViolation(RuntimeError):
    """Raised when a consumer attempts to order spans across a clock-domain break."""
    pass


def order_spans(spans: list[dict]) -> list[dict]:
    """
    Reconstruct causal order. Timestamp sort is only legal within a single
    clock domain; across a clk_break the order is unknown and must be resolved
    by parent-edge walk, never by start_time.
    """
    domains = {s.get("clk_domain", "upstream") for s in spans}
    breaks = [s for s in spans if s.get("causality.break")]

    if breaks and len(domains) > 1:
        # We have spans from >1 clock domain and at least one explicit break.
        # Sorting by start_time here would fabricate an order.
        raise CausalOrderViolation(
            f"cannot timestamp-order {len(spans)} spans across "
            f"{len(domains)} clock domains with {len(breaks)} causality breaks; "
            f"resolve via parent_span_id walk instead"
        )

    # Single domain (or no breaks): timestamp sort is sound.
    return sorted(spans, key=lambda s: s["start_time"])


def verify_handoff(parent: dict, child: dict) -> None:
    """Enforce the handoff invariant before a child span is emitted."""
    if child.get("clk_domain") != parent.get("clk_domain") and not child.get("causality.break"):
        raise CausalOrderViolation(
            f"hop {parent['span_id']}->{child['span_id']} changed clock domain "
            f"({parent.get('clk_domain')}->{child.get('clk_domain')}) "
            f"without setting causality.break; child start_time would be "
            f"unorderable against parent end_time"
        )
