# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-do-equal-timestamps-make-replay-order-non-deterministic.md
# Remnant Warrant:    https://corpusfetch.com/c/when-do-equal-timestamps-make-replay-order-non-deterministic.warrant.json
# Markdown SHA-256:   da508662981ad7ac50d8f56d7eb4620f5faf0c5337e113a343128b648404ab4c
# Code AST SHA-256:   57b67ca43b9b64be5b073cbc733fb4090e4f522effeb6c98d30a8e24e2541750
# Verified Classes:   ReplayOrderError, ReplayOrderGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ReplayOrderError(RuntimeError):
    """Raised when the replay order key is not a total order over the event set."""


@dataclass(frozen=True)
class ReplayOrderGate:
    order_key_fields: tuple
    events_commutative: bool = False

    def verify(self) -> bool:
        if self.events_commutative:
            return True
        if "timestamp" in self.order_key_fields and len(self.order_key_fields) == 1:
            raise ReplayOrderError(
                "timestamp alone is not a total order at coarse resolution"
            )
        if not self.order_key_fields:
            raise ReplayOrderError("no order key: storage order will be used")
        return True


def dispatch_replay_mode(gate: ReplayOrderGate) -> str:
    try:
        gate.verify()
    except ReplayOrderError:
        return "add-monotonic-tiebreaker"
    return "ordered-replay"
