# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-replay-a-multi-agent-run-to-a-different-verdict-non-commutative-span-reordering-in-opentelemetry-genai-graph-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-replay-a-multi-agent-run-to-a-different-verdict-non-commutative-span-reordering-in-opentelemetry-genai-graph-reconstruction.warrant.json
# Markdown SHA-256:   cf0f9179d0018e181fd1e6018e457ab1ba5d7192de7af8193dbe92e51e4c4fed
# Code AST SHA-256:   2f6ef54e3f5cd3e89b9e31582bfcc6d7d29d103a593d379a9848cb7397f296b9
# Verified Classes:   AmbiguousLinearizationError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class AmbiguousLinearizationError(RuntimeError):
    """Raised when replay must order two spans with no happens-before edge."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_id: str | None
    start_ns: int
    touches: frozenset[str]          # shared mutable resources written/read
    seq: int | None = None           # monotonic witness, if instrumented


def happens_before(a: Span, b: Span, spans: dict[str, Span]) -> bool:
    # Ancestor walk: a precedes b if a is an ancestor of b.
    cur = spans.get(b.parent_id) if b.parent_id else None
    while cur is not None:
        if cur.span_id == a.span_id:
            return True
        cur = spans.get(cur.parent_id) if cur.parent_id else None
    # Explicit sequence witness disambiguates concurrent siblings.
    if a.seq is not None and b.seq is not None and a.parent_id == b.parent_id:
        return a.seq < b.seq
    return False


def linearize(siblings: list[Span], spans: dict[str, Span],
              clock_resolution_ns: int) -> list[Span]:
    """Sort siblings, but refuse when the sort would invent an order."""
    ordered = sorted(siblings, key=lambda s: (s.start_ns, s.seq if s.seq is not None else -1))
    for i in range(len(ordered) - 1):
        a, b = ordered[i], ordered[i + 1]
        if happens_before(b, a, spans):
            continue  # sort already consistent with this edge
        unordered = not happens_before(a, b, spans)
        close = abs(a.start_ns - b.start_ns) < clock_resolution_ns
        shared = a.touches & b.touches
        if unordered and close and shared:
            raise AmbiguousLinearizationError(
                f"cannot order {a.span_id} vs {b.span_id}: no happens-before edge, "
                f"timestamps within {clock_resolution_ns}ns, shared resource(s) "
                f"{sorted(shared)}; replay would fabricate a schedule. "
                f"Pin a sequence witness or enumerate the linearization lattice."
            )
    return ordered


def replay_counterfactual(spans: dict[str, Span], clock_resolution_ns: int,
                          baseline_verdict: str) -> str:
    roots = [s for s in spans.values() if s.parent_id is None]
    if not roots:
        raise AmbiguousLinearizationError("empty trace: no root span to anchor replay")
    schedule = linearize(roots, spans, clock_resolution_ns)
    # ... execute schedule under pinned linearization ...
    return baseline_verdict
