# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-invariants-prevent-cancellation-from-racing-with-already-dispatched-work.md
# Remnant Warrant:    https://corpusfetch.com/c/what-invariants-prevent-cancellation-from-racing-with-already-dispatched-work.warrant.json
# Markdown SHA-256:   6ec8c29f990191de27f7c7e0a8dc58d328b6c3185187a8a0d7162022e2ead66b
# Code AST SHA-256:   8ccc4acda5aaacedfd357f99c0314403ceb0ba569129987a4f30048ce136ce5a
# Verified Classes:   CancelRaceError, CancelGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class CancelRaceError(RuntimeError):
    """Raised when cancellation can race with a side-effect commit and cannot compensate."""


@dataclass(frozen=True)
class CancelGate:
    cancel_deadline_defined: bool
    cancel_arrives_before_commit: bool
    work_compensable: bool
    compensation_available: bool = True

    def verify(self) -> bool:
        if not self.cancel_deadline_defined:
            raise CancelRaceError(
                "cancel deadline undefined: effective-versus-post-commit boundary is undecidable"
            )
        if self.cancel_arrives_before_commit:
            return True
        if self.work_compensable and self.compensation_available:
            return True
        raise CancelRaceError(
            "cancel arrives after commit and work has no compensation: side effect will persist"
        )


def dispatch_cancel_mode(gate: CancelGate) -> str:
    try:
        gate.verify()
    except CancelRaceError:
        return "surface-post-commit-side-effect"
    return "cancel-effective"
