# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-swarm-execution-from-otel-spans-and-the-causal-order-collapses-under-concurrent-partial-batch-emission.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-swarm-execution-from-otel-spans-and-the-causal-order-collapses-under-concurrent-partial-batch-emission.warrant.json
# Markdown SHA-256:   5ef89641eae6232edad3ebc57e599c4a309fab032c9870a52e1257949b1f9378
# Code AST SHA-256:   476730f86532c4427e990a768c48a2b9adaae2d37117eea523a53d1037e8ec73
# Verified Classes:   ReplayOrderingError, Order, Span, Trace
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ReplayOrderingError(RuntimeError):
    """Raised when a replay cannot produce a causally valid ordering."""


class Order(Enum):
    CAUSAL_BEFORE = "causal_before"
    CAUSAL_AFTER = "causal_after"
    WALLCLOCK_TRUSTED = "wallclock_trusted"
    INDETERMINATE = "indeterminate"


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_id: Optional[str]
    start_ns: int
    service: str
    links: tuple[str, ...] = ()


@dataclass
class Trace:
    spans: dict[str, Span] = field(default_factory=dict)
    # per-service epoch skew bound in ns, derived from paired spans
    skew_bound_ns: dict[str, int] = field(default_factory=dict)

    def happens_before(self, a: str, b: str) -> bool:
        """True if a is an ancestor of b via parent/link edges (excluding self)."""
        seen: set[str] = set()
        stack = [b]
        while stack:
            cur = stack.pop()
            if cur in seen:
                continue
            seen.add(cur)
            s = self.spans.get(cur)
            if s is None:
                continue
            preds = ([s.parent_id] if s.parent_id else []) + list(s.links)
            for p in preds:
                if p == a:
                    return True
                if p:
                    stack.append(p)
        return False

    def order_pair(self, a: str, b: str) -> Order:
        if self.happens_before(a, b):
            return Order.CAUSAL_BEFORE
        if self.happens_before(b, a):
            return Order.CAUSAL_AFTER
        sa, sb = self.spans[a], self.spans[b]
        gap = abs(sa.start_ns - sb.start_ns)
        bound = max(
            self.skew_bound_ns.get(sa.service, 0),
            self.skew_bound_ns.get(sb.service, 0),
        )
        if bound == 0:
            # no paired-span evidence: timestamp ordering is unverifiable
            return Order.INDETERMINATE
        if gap > bound:
            return Order.WALLCLOCK_TRUSTED
        return Order.INDETERMINATE


def assert_replayable(trace: Trace, required_pairs: list[tuple[str, str]]) -> None:
    """Verify that every pair a forensic conclusion depends on is ordered.

    Raises ReplayOrderingError if any required pair is INDETERMINATE, because
    a conclusion resting on an indeterminate pair is not supported by the trace.
    """
    for a, b in required_pairs:
        if a not in trace.spans or b not in trace.spans:
            raise ReplayOrderingError(
                f"missing span in required pair ({a}, {b}); trace is incomplete"
            )
        o = trace.order_pair(a, b)
        if o is Order.INDETERMINATE:
            raise ReplayOrderingError(
                f"cannot order ({a}, {b}): no causal edge and timestamp gap "
                f"within skew bound; conclusion is underdetermined by trace"
            )
        if o is Order.CAUSAL_AFTER:
            # caller assumed a-before-b but causal graph says otherwise:
            # a timestamp-sorted replay would have silently inverted this.
            raise ReplayOrderingError(
                f"causal order contradicts requested order for ({a}, {b}): "
                f"b happens-before a via span graph"
            )
