# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-single-trace-causal-reconstruction-when-a-federated-tool-invocation-graph-forks-across-agents-that-share-no.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-single-trace-causal-reconstruction-when-a-federated-tool-invocation-graph-forks-across-agents-that-share-no.warrant.json
# Markdown SHA-256:   dfedeb757e432b317514d58e194df9c532bc869321c2b97bfa382d9848cdae29
# Code AST SHA-256:   3a682825bbacf814ec2a0d8e82e6ea5464480671cef68eb66ddcc4e6a02ea841
# Verified Classes:   CausalOrderViolation, Span, ReconstructedGraph
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class CausalOrderViolation(RuntimeError):
    """Raised when reconstruction is asked for a total order it cannot justify."""
    pass


@dataclass
class Span:
    span_id: str
    agent_id: str
    tool: str
    start_ts: float
    end_ts: float
    parent_span_id: Optional[str] = None
    traceparent: Optional[str] = None
    input_digest: Optional[str] = None
    task_id: str = ""


@dataclass
class ReconstructedGraph:
    total_order: Optional[list] = None
    concurrent_sets: list = field(default_factory=list)
    token_coverage: float = 0.0
    cycles: list = field(default_factory=list)


def _has_causal_token(upstream: Span, downstream: Span) -> bool:
    if downstream.parent_span_id == upstream.span_id:
        return True
    if downstream.traceparent and upstream.span_id in downstream.traceparent:
        return True
    if downstream.input_digest and upstream.input_digest == downstream.input_digest:
        return True
    return False


def reconstruct(spans: list[Span], clock_error_bound: float) -> ReconstructedGraph:
    """Reconstruct causal order across federated spans.

    clock_error_bound: one-sided max skew epsilon across hosts, in seconds.
    """
    if not spans:
        return ReconstructedGraph(total_order=[])

    # Group by task; correlation ID is co-membership, NOT causal order.
    by_task: dict[str, list[Span]] = {}
    for s in spans:
        by_task.setdefault(s.task_id, []).append(s)

    graph = ReconstructedGraph()
    tokened_edges = 0
    total_cross_edges = 0

    for task_id, group in by_task.items():
        agents = {s.agent_id for s in group}
        if len(agents) == 1:
            # Single-agent: timestamp order is safe within one clock domain.
            graph.total_order = sorted(group, key=lambda s: s.start_ts)
            continue

        # Cross-agent: every pair must be justified by a token or declared concurrent.
        unresolved = []
        for i, a in enumerate(group):
            for b in group[i + 1:]:
                if a.agent_id == b.agent_id:
                    continue
                total_cross_edges += 1
                if _has_causal_token(a, b) or _has_causal_token(b, a):
                    tokened_edges += 1
                else:
                    gap = abs(a.start_ts - b.start_ts)
                    if gap <= 2 * clock_error_bound:
                        unresolved.append((a, b))

        if unresolved:
            # Cannot assert total order. Refuse, do not guess.
            graph.concurrent_sets.extend(unresolved)
            graph.total_order = None
        else:
            graph.total_order = sorted(group, key=lambda s: s.start_ts)

    graph.token_coverage = (
        tokened_edges / total_cross_edges if total_cross_edges else 1.0
    )
    return graph


def assert_total_order(graph: ReconstructedGraph, query: str) -> list:
    """Caller asks a happens-before question; enforce the invariant."""
    if graph.total_order is None:
        raise CausalOrderViolation(
            f"Cannot answer '{query}': cross-agent edges lack causal tokens "
            f"and fall within clock-skew window. token_coverage="
            f"{graph.token_coverage:.2f}. Fix A2A trace-context propagation; "
            f"do not sort by timestamp."
        )
    return graph.total_order
