# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconstruct-a-causal-trace-across-federated-agent-hops-when-span-identifiers-are-minted-per-hop-and-never-reconciled.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconstruct-a-causal-trace-across-federated-agent-hops-when-span-identifiers-are-minted-per-hop-and-never-reconciled.warrant.json
# Markdown SHA-256:   a32926ec8f82b2d1b7b90a1df76099d420e7e26f760747517367fb4db07ff69a
# Code AST SHA-256:   74d687940ddc495b28c0478ac941f628279bf6b2de77ed70bbdfb26a9aea0afd
# Verified Classes:   TraceReconstructionRefused, EdgeProvenance, Span, CausalEdge
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class TraceReconstructionRefused(RuntimeError):
    """Raised when a federated trace cannot be soundly fused across a hop."""


class EdgeProvenance(Enum):
    ASSERTED = "asserted"   # parent reference carried in the A2A/MCP envelope
    INFERRED = "inferred"   # reconstructed from timestamp ordering


@dataclass(frozen=True)
class Span:
    hop: str
    span_id: str
    parent_span_id: str | None
    join_key: str
    start_ts_ms: int          # stamped by the hop's own clock
    clock_domain: str         # identifies the hop's clock; skew is opaque across domains


@dataclass
class CausalEdge:
    parent: Span
    child: Span
    provenance: EdgeProvenance


def _join_key_is_injective(spans: list[Span]) -> bool:
    # A join key is injective only if every span sharing it belongs to one causal
    # chain. We approximate by requiring that a shared join key never maps two
    # distinct root spans (parent_span_id is None) to the same key.
    roots_by_key: dict[str, set[str]] = {}
    for s in spans:
        if s.parent_span_id is None:
            roots_by_key.setdefault(s.join_key, set()).add(s.span_id)
    return all(len(roots) <= 1 for roots in roots_by_key.values())


def reconstruct_causal_trace(spans: list[Span]) -> list[CausalEdge]:
    if not _join_key_is_injective(spans):
        raise TraceReconstructionRefused(
            "non_injective_join_key: a shared join_key maps to multiple root "
            "spans; fusing would alias distinct causal chains"
        )

    by_span_id = {s.span_id: s for s in spans}
    edges: list[CausalEdge] = []

    for s in spans:
        if s.parent_span_id is None:
            continue
        parent = by_span_id.get(s.parent_span_id)
        if parent is None:
            # Parent lives in another hop and was not carried; cannot assert edge.
            raise TraceReconstructionRefused(
                f"missing_asserted_parent: span {s.span_id} references "
                f"{s.parent_span_id} which was not propagated across hop {s.hop}"
            )
        if parent.clock_domain != s.clock_domain and parent.start_ts_ms > s.start_ts_ms:
            # Cross-domain ordering by wall clock is a category error.
            raise TraceReconstructionRefused(
                f"inferred_cross_clock_edge: {parent.span_id}->{s.span_id} "
                f"spans clock domains {parent.clock_domain}/{s.clock_domain}"
            )
        edges.append(CausalEdge(parent, s, EdgeProvenance.ASSERTED))

    return edges


def admit_to_actionable_trace(edges: list[CausalEdge]) -> list[CausalEdge]:
    actionable = [e for e in edges if e.provenance is EdgeProvenance.ASSERTED]
    if len(actionable) != len(edges):
        raise TraceReconstructionRefused(
            "inferred_edges_present: automated remediation may not consume "
            "causally unverified edges"
        )
    return actionable
