# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-on-quorum-alone-equivocation-safe-commitment-under-partial-synchrony.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-on-quorum-alone-equivocation-safe-commitment-under-partial-synchrony.warrant.json
# Markdown SHA-256:   3468d1fccf308659d5b4398e3440a60f9d37bf5a494a1f6aca82af06fbf7784a
# Code AST SHA-256:   95ac8ace3cb57c3695ba0b4d2b8fa15a51888452a4e1fe1f6a32680178daf047
# Verified Classes:   CommitmentSafetyError, CommitmentLayer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CommitmentSafetyError(RuntimeError):
    """Raised when a commit is attempted without satisfying the commitment predicate.

    A valid quorum certificate is necessary but not sufficient for commit under
    Byzantine faults. This error signals that the predicate (two-phase commit
    certificate, crash-fault model, or verified view-change fencing) is unmet,
    or that a conflicting QC has been observed at the same sequence number.
    """
    pass


class CommitmentLayer:
    def __init__(self, fault_model: str, non_equivocation_enforced: bool):
        # fault_model: "crash" or "byzantine"
        self.fault_model = fault_model
        self.non_equivocation_enforced = non_equivocation_enforced
        # seq -> value committed (or None)
        self.committed = {}
        # seq -> set of values for which a valid QC has been observed
        self.certified = {}
        # seq -> bool: view-change fencing proof verified for current view
        self.fenced = {}

    def _predicate_holds(self, seq: int, qc_value: str, commit_cert: bool) -> bool:
        # (a) two-phase commit certificate present
        if commit_cert:
            return True
        # (b) crash-fault model or externally enforced non-equivocation
        if self.fault_model == "crash" or self.non_equivocation_enforced:
            return True
        # (c) verified view-change fencing for this sequence
        if self.fenced.get(seq, False):
            return True
        return False

    def observe_qc(self, seq: int, value: str) -> None:
        self.certified.setdefault(seq, set()).add(value)

    def commit(self, seq: int, value: str, commit_cert: bool = False) -> None:
        # Record the QC observation first so conflicts are detectable.
        self.observe_qc(seq, value)

        prior = self.certified.get(seq, set())
        if len(prior) > 1:
            # Two distinct values certified at the same sequence number:
            # equivocation. Do not pick a winner.
            raise CommitmentSafetyError(
                f"equivocation at seq={seq}: conflicting certified values {sorted(prior)}"
            )

        if not self._predicate_holds(seq, value, commit_cert):
            raise CommitmentSafetyError(
                f"refusing commit at seq={seq} value={value!r}: "
                f"quorum certificate present but commitment predicate unmet "
                f"(fault_model={self.fault_model}, "
                f"non_equivocation_enforced={self.non_equivocation_enforced}, "
                f"commit_cert={commit_cert}, fenced={self.fenced.get(seq, False)})"
            )

        if seq in self.committed and self.committed[seq] != value:
            raise CommitmentSafetyError(
                f"double-commit at seq={seq}: already committed {self.committed[seq]!r}, "
                f"now asked to commit {value!r}"
            )

        self.committed[seq] = value


# Example: Byzantine model, no non-equivocation, no fencing, no commit cert.
layer = CommitmentLayer(fault_model="byzantine", non_equivocation_enforced=False)
layer.observe_qc(7, "A")
try:
    layer.commit(7, "A")  # valid QC, but predicate unmet -> must refuse
except CommitmentSafetyError as e:
    print("refused:", e)

# Equivocation case: a conflicting QC arrives for the same sequence.
layer.observe_qc(7, "A'")
try:
    layer.commit(7, "A'")
except CommitmentSafetyError as e:
    print("refused:", e)
