# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trace-correlation-collapse-when-federated-agent-spans-cross-trust-boundaries-with-lossy-context-propagation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trace-correlation-collapse-when-federated-agent-spans-cross-trust-boundaries-with-lossy-context-propagation.warrant.json
# Markdown SHA-256:   c741dfcf74c01e6db9225d7b03645533495dd8180282a13e1c4786e7efa2d9c0
# Code AST SHA-256:   1ae2c3ebb648f0b9271874b83b1567698bde57834646bfa50e74ca3673ce07b5
# Verified Classes:   CorrelationCollapseError, Span, DispatchRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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

# Declared tolerance for cross-org clock skew, in seconds.
CLOCK_SKEW_TOLERANCE_S = 1.0
# Minimum fraction of dispatched subtasks that must have a matched executor span.
MIN_CORRELATION_COVERAGE = 0.95


class CorrelationCollapseError(RuntimeError):
    """Raised when federated spans cannot be joined into a causally valid trace."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    org: str
    substrate_version: str
    sampled: bool
    start_time: float
    clock_offset_s: float = 0.0


@dataclass
class DispatchRecord:
    trace_id: str
    subtask_id: str
    dispatched_at: float


def join_federated_trace(
    dispatches: list[DispatchRecord],
    spans: list[Span],
    expected_substrate: str,
) -> dict:
    by_trace: dict[str, list[Span]] = {}
    for s in spans:
        by_trace.setdefault(s.trace_id, []).append(s)

    verdicts = {}
    matched_dispatches = 0

    for d in dispatches:
        candidates = by_trace.get(d.trace_id, [])
        if not candidates:
            verdicts[d.subtask_id] = ("ORPHANED", "no executor span for trace_id")
            continue

        executor_spans = [s for s in candidates if s.org != "planner"]
        if not executor_spans:
            verdicts[d.subtask_id] = ("ORPHANED", "no cross-org span under trace_id")
            continue

        bad_substrate = [s for s in executor_spans if s.substrate_version != expected_substrate]
        if bad_substrate:
            verdicts[d.subtask_id] = (
                "DEGRADED",
                f"substrate mismatch: {bad_substrate[0].substrate_version}",
            )
            continue

        dropped = [s for s in executor_spans if not s.sampled]
        if len(dropped) == len(executor_spans):
            verdicts[d.subtask_id] = ("DEGRADED", "all executor spans dropped by sampler")
            continue

        planner = next((s for s in candidates if s.org == "planner"), None)
        if planner is None:
            verdicts[d.subtask_id] = ("ORPHANED", "planner span absent from store")
            continue

        skew = abs(executor_spans[0].clock_offset_s - planner.clock_offset_s)
        if skew > CLOCK_SKEW_TOLERANCE_S:
            verdicts[d.subtask_id] = ("DEGRADED", f"clock skew {skew:.2f}s exceeds tolerance")
            continue

        verdicts[d.subtask_id] = ("MATCHED", "")
        matched_dispatches += 1

    coverage = matched_dispatches / len(dispatches) if dispatches else 0.0
    if coverage < MIN_CORRELATION_COVERAGE:
        degraded = [k for k, (v, _) in verdicts.items() if v != "MATCHED"]
        raise CorrelationCollapseError(
            f"correlation coverage {coverage:.2%} below invariant "
            f"{MIN_CORRELATION_COVERAGE:.0%}; degraded subtasks: {degraded[:5]}"
        )

    return {"coverage": coverage, "verdicts": verdicts}
