# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-causal-trace-ordering-when-federated-agents-exchange-spans-across-skewed-clocks.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-causal-trace-ordering-when-federated-agents-exchange-spans-across-skewed-clocks.warrant.json
# Markdown SHA-256:   1202246a510dcd954a307e89c9b6a9b72fa3e11643a35bf56558da890dcc56a4
# Code AST SHA-256:   c19536cd19ac3b32e17591d203886ea784877369bc8ded5f89b71e484801aab3
# Verified Classes:   CausalOrderViolation, SkewUnmeasured
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CausalOrderViolation(RuntimeError):
    """Raised when a trace merge would assert a causal order that contradicts the span-link partial order."""
    pass


class SkewUnmeasured(CausalOrderViolation):
    """Raised when timestamp-primary ordering is requested for an agent with no bounded skew estimate."""
    pass


def merge_federated_trace(spans, skew_bounds, strategy="causal"):
    # spans: list of dicts with id, parent, agent, start_local, end_local
    # skew_bounds: {agent: epsilon_ms}; missing agent => unbounded
    by_id = {s["id"]: s for s in spans}

    if strategy == "timestamp":
        # Only admissible if every agent has a measured, bounded skew.
        for s in spans:
            if s["agent"] not in skew_bounds:
                raise SkewUnmeasured(
                    f"agent {s['agent']!r} has no measured skew bound; "
                    f"timestamp-primary ordering is unsound"
                )
        eps = max(skew_bounds.values())
        gaps = _min_handoff_gap(spans)
        if eps * 2 >= gaps:
            raise CausalOrderViolation(
                f"skew bound {eps}ms >= half min handoff gap {gaps}ms; "
                f"timestamps cannot order spans"
            )

    # Causal-primary: topological sort over span links.
    order = _toposort(by_id)
    if order is None:
        raise CausalOrderViolation(
            "span-link graph contains a cycle; trace is genuinely corrupt"
        )

    # Timestamps are corrected for display only, never for ordering.
    for s in order:
        s["start_corrected"] = s["start_local"] - skew_bounds.get(s["agent"], 0)
    return order


def _toposort(by_id):
    children = {sid: [] for sid in by_id}
    indeg = {sid: 0 for sid in by_id}
    for sid, s in by_id.items():
        p = s.get("parent")
        if p and p in by_id:
            children[p].append(sid)
            indeg[sid] += 1
    queue = [sid for sid, d in indeg.items() if d == 0]
    out = []
    while queue:
        sid = queue.pop(0)
        out.append(by_id[sid])
        for c in children[sid]:
            indeg[c] -= 1
            if indeg[c] == 0:
                queue.append(c)
    return out if len(out) == len(by_id) else None


def _min_handoff_gap(spans):
    gaps = []
    by_id = {s["id"]: s for s in spans}
    for s in spans:
        p = s.get("parent")
        if p and p in by_id:
            gaps.append(abs(s["start_local"] - by_id[p]["end_local"]))
    return min(gaps) if gaps else 0
