# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-does-an-unstable-sort-reorder-equal-elements-and-break-downstream-assumptions.md
# Remnant Warrant:    https://corpusfetch.com/c/when-does-an-unstable-sort-reorder-equal-elements-and-break-downstream-assumptions.warrant.json
# Markdown SHA-256:   f5f1242d31e249ad87cd04396bbbc9ec6e560c944944dc6f5aaa43eb8bb6d61b
# Code AST SHA-256:   544a565681741f6774ce8b073f1b542f52c68c8cbc5fe98aee24209416d9bfd8
# Verified Classes:   SortStabilityError, SortStabilityGate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SortStabilityError(RuntimeError):
    """Raised when downstream assumptions depend on an unstable sort of equal elements."""


@dataclass(frozen=True)
class SortStabilityGate:
    sort_is_stable: bool
    tiebreaker_present: bool
    downstream_order_dependent: bool = True

    def verify(self) -> bool:
        if not self.downstream_order_dependent:
            return True
        if not self.sort_is_stable and not self.tiebreaker_present:
            raise SortStabilityError(
                "unstable sort with order-dependent downstream: equal elements may reorder"
            )
        return True


def dispatch_sort_mode(gate: SortStabilityGate) -> str:
    try:
        gate.verify()
    except SortStabilityError:
        return "add-tiebreaker"
    return "as-configured"
