# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-withhold-plan-commitment-when-a-byzantine-peer-can-equivocate-across-quorum-slices.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-withhold-plan-commitment-when-a-byzantine-peer-can-equivocate-across-quorum-slices.warrant.json
# Markdown SHA-256:   7ba6959397f1bd9a42ca74e075370090c861f52f4e5c903764f92831dc507bb4
# Code AST SHA-256:   4debbf972368356de4b1f21bb49a65d30f34e2dc54bf8d6d94af428e25c00bec
# Verified Classes:   SliceDivergenceError, QuorumCertificate, PlanCommitGuard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class SliceDivergenceError(RuntimeError):
    """Raised when an instance is asked to commit a plan whose hash conflicts
    with an already-signed PREPARE, while belonging to multiple quorum slices."""


@dataclass
class QuorumCertificate:
    plan_id: str
    steps_hash: str
    signers: frozenset


@dataclass
class PlanCommitGuard:
    my_slices: list            # list[frozenset[str]] — slices this instance belongs to
    threshold: int             # ratification threshold per slice
    signed_prepares: dict = field(default_factory=dict)  # plan_id -> steps_hash

    def _covers_all_slices(self, signers: frozenset) -> bool:
        return all(len(signers & s) >= 1 for s in self.my_slices)

    def observe_prepare(self, plan_id: str, steps_hash: str, signer: str) -> None:
        prior = self.signed_prepares.get(plan_id)
        if prior is not None and prior != steps_hash and len(self.my_slices) > 1:
            raise SliceDivergenceError(
                f"equivocation on plan {plan_id}: signed {prior}, now see {steps_hash} "
                f"from {signer}; instance spans {len(self.my_slices)} slices — freeze"
            )
        self.signed_prepares.setdefault(plan_id, steps_hash)

    def try_commit(self, qc: QuorumCertificate) -> bool:
        if qc.steps_hash != self.signed_prepares.get(qc.plan_id):
            raise SliceDivergenceError(
                f"commit hash {qc.steps_hash} for {qc.plan_id} diverges from signed prepare"
            )
        if len(self.my_slices) > 1 and not self._covers_all_slices(qc.signers):
            # Cannot rule out a second divergent commit in a slice we can't see.
            return False
        if len(qc.signers) < self.threshold:
            return False
        return True
