# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-reconstructed-causal-trace-monotonic-epoch-violation-as-the-boundary-condition-for-federated-agent-observability.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-reconstructed-causal-trace-monotonic-epoch-violation-as-the-boundary-condition-for-federated-agent-observability.warrant.json
# Markdown SHA-256:   cfbaa9a63f265673744dbcccd9e964d451fabb841d0488990bf804e3cd79a318
# Code AST SHA-256:   7aeb63cae06d8f55d8eb98078bb6523b039b27d4732934318c665e5aed04100b
# Verified Classes:   CausalTraceRewindError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalTraceRewindError(RuntimeError):
    """Raised when a reconstructed federated trace violates epoch monotonicity."""
    pass


@dataclass
class Span:
    span_id: str
    trace_id: str
    parent_id: Optional[str]
    instance_id: str
    logical_epoch: int
    emitted_at: float
    replay: bool = False
    original_span_id: Optional[str] = None


def validate_trace(spans: list[Span]) -> str:
    """Return VALID / DEGRADED_REPLAY / QUARANTINED_REWIND.

    Raises CausalTraceRewindError when a rewind cannot be explained by replay tags.
    """
    by_id = {s.span_id: s for s in spans}
    replayed_originals = {s.original_span_id for s in spans if s.replay}

    for span in spans:
        if span.parent_id is None:
            continue
        parent = by_id.get(span.parent_id)
        if parent is None:
            continue

        # Rewind: child logically precedes parent on the same causal path.
        if span.logical_epoch < parent.logical_epoch:
            explained = (
                span.replay
                and span.original_span_id in by_id
                and by_id[span.original_span_id].logical_epoch <= parent.logical_epoch
            )
            if not explained:
                raise CausalTraceRewindError(
                    f"span {span.span_id} (epoch {span.logical_epoch}) "
                    f"precedes parent {parent.span_id} (epoch {parent.logical_epoch}) "
                    f"with no valid replay provenance"
                )

        # Clock-skew masquerade: child emitted before parent but claims later epoch.
        if span.emitted_at < parent.emitted_at and span.logical_epoch > parent.logical_epoch:
            raise CausalTraceRewindError(
                f"span {span.span_id} emitted_at precedes parent {parent.span_id} "
                f"but claims later logical epoch; clock skew not causality"
            )

    if replayed_originals:
        return "DEGRADED_REPLAY"
    return "VALID"


def causal_attribution(spans: list[Span], verdict_epoch: int) -> Span:
    """Last non-replay span strictly before the verdict epoch, in logical order."""
    candidates = [
        s for s in spans
        if not s.replay and s.logical_epoch < verdict_epoch
    ]
    if not candidates:
        raise CausalTraceRewindError(
            f"no causally prior non-replay span before epoch {verdict_epoch}"
        )
    return max(candidates, key=lambda s: s.logical_epoch)
