# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-replay-a-multi-agent-tool-call-dag-deterministically-when-non-idempotent-tools-and-clock-skewed-timestamps-make-the-trace-order.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-replay-a-multi-agent-tool-call-dag-deterministically-when-non-idempotent-tools-and-clock-skewed-timestamps-make-the-trace-order.warrant.json
# Markdown SHA-256:   1e42176e6bc59bda520db55a59cd1452d66556ccaaa8828ecb03bc32f6d2c5ee
# Code AST SHA-256:   db86fcd9c79d97206d6e5f35d34405a9f37a6fa02d295c0c581f80c370ab36c2
# Verified Classes:   ReplayMode, Span, OrderAmbiguousNonReconstructible, ToolInvocationDuringReplay
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ReplayMode(Enum):
    RECONSTRUCT = "reconstruct"
    REEXECUTE = "reexecute"


@dataclass
class Span:
    span_id: str
    tool: str
    logical_clock: int | None          # Lamport counter, if emitted
    start_ts: float                    # wall clock, possibly skewed
    recorded_result: dict[str, Any] | None
    idempotent: bool
    time_sensitive: bool
    happens_before: set[str] = field(default_factory=set)


class OrderAmbiguousNonReconstructible(RuntimeError):
    """Raised when replay cannot order non-idempotent spans from the trace alone."""


class ToolInvocationDuringReplay(RuntimeError):
    """Raised if replay attempts to invoke a live tool instead of substituting a result."""


def resolve_order(spans: list[Span]) -> list[Span]:
    # Prefer logical clocks; fall back to wall clock only under strict conditions.
    has_logical = all(s.logical_clock is not None for s in spans)
    if has_logical:
        return sorted(spans, key=lambda s: s.logical_clock)  # type: ignore[arg-type]

    ordered = sorted(spans, key=lambda s: s.start_ts)
    # Wall-clock ties or near-ties among risky spans are not resolvable.
    for a, b in zip(ordered, ordered[1:]):
        if abs(b.start_ts - a.start_ts) < 0.250:  # skew tolerance window
            risky = [s for s in (a, b) if not s.idempotent or s.time_sensitive]
            if risky:
                raise OrderAmbiguousNonReconstructible(
                    f"spans {a.span_id} and {b.span_id} are within clock-skew "
                    f"tolerance and at least one ({[s.span_id for s in risky]}) "
                    f"is non-idempotent or time-sensitive; trace cannot order them"
                )
    return ordered


def replay(trace: list[Span], mode: ReplayMode) -> list[Span]:
    if mode is not ReplayMode.RECONSTRUCT:
        raise ToolInvocationDuringReplay(
            "forensic replay must operate in RECONSTRUCT mode; "
            "re-execution is a distinct operation"
        )
    for span in trace:
        if span.recorded_result is None:
            raise ToolInvocationDuringReplay(
                f"span {span.span_id} ({span.tool}) has no recorded result; "
                f"replay would have to invoke the tool to reconstruct state"
            )
    return resolve_order(trace)
