# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-trace-join-as-evidence-destroying-rather-than-merely-incomplete.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-trace-join-as-evidence-destroying-rather-than-merely-incomplete.warrant.json
# Markdown SHA-256:   59df51b8e7411aa9c0db011d0edfde0e00bf2f21b7fea26d9a574cbc2a974642
# Code AST SHA-256:   f74dc1b9fa7cdb78e119635cd245f0fe6d78358580cbdeb9cb622fb120d890e9
# Verified Classes:   FederatedJoinCorruption, Span, JoinResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class FederatedJoinCorruption(RuntimeError):
    """Raised when a cross-org trace join would produce a closed but causally
    false reconstruction (re-minted identity or clock-derived ordering)."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    org: str
    start_ns: int
    tracestate: Optional[str]


@dataclass
class JoinResult:
    graph: dict = field(default_factory=dict)
    unjoined: list = field(default_factory=list)
    verdict: str = "complete"


def federated_join(spans: list, incident_trace_id: str) -> JoinResult:
    """Join spans across orgs on trace_id, but refuse to emit a closed graph
    when identity was re-minted or a parent dangles across a trust boundary."""
    by_trace = {}
    for s in spans:
        by_trace.setdefault(s.trace_id, []).append(s)

    incident = by_trace.get(incident_trace_id, [])
    if not incident:
        raise FederatedJoinCorruption(
            f"incident trace {incident_trace_id} has no spans; refusing empty join"
        )

    result = JoinResult(graph={s.span_id: s for s in incident})

    # Detect re-minted identity: a span in the incident trace whose parent
    # lives in a *different* trace is a severed causal edge, not an orphan.
    span_ids = {s.span_id for s in incident}
    for s in incident:
        if s.parent_span_id and s.parent_span_id not in span_ids:
            elsewhere = [
                o for t, group in by_trace.items() if t != incident_trace_id
                for o in group if o.span_id == s.parent_span_id
            ]
            if elsewhere:
                result.unjoined.append((s, elsewhere[0]))
                result.verdict = "incomplete"

    # Detect clock-derived ordering: if any unjoined parent is timestamped
    # after its child, the join would invert causality under a sort.
    for child, parent in result.unjoined:
        if parent.start_ns > child.start_ns:
            raise FederatedJoinCorruption(
                f"span {child.span_id} (org {child.org}) would be ordered before "
                f"its cross-org parent {parent.span_id} (org {parent.org}) by "
                f"{(parent.start_ns - child.start_ns) / 1e9:.2f}s clock drift; "
                f"join is evidence-destroying, quarantine and reconstruct from "
                f"handoff receipts"
            )

    # Detect lost tracestate across a resume boundary (re-minted trace).
    for s in incident:
        if s.parent_span_id is None and s.tracestate is None and s.org != incident[0].org:
            raise FederatedJoinCorruption(
                f"resumed span {s.span_id} in org {s.org} lacks tracestate; "
                f"identity continuity unproven, join unsound"
            )

    if result.verdict != "complete":
        raise FederatedJoinCorruption(
            f"join for {incident_trace_id} has {len(result.unjoined)} unjoined "
            f"cross-org edges; refusing to return a closed graph as evidence"
        )
    return result
