# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-plan-commitments-before-byzantine-quorum-finalization-collapses.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-plan-commitments-before-byzantine-quorum-finalization-collapses.warrant.json
# Markdown SHA-256:   ecdbcbb732f1c0d9cc13d28771461dbd677a4b81e8622b91d52bc245c8669939
# Code AST SHA-256:   592794c9ed4c86371c923c84ae7a4310c926911222a5e20a168d12c4d1de551b
# Verified Classes:   CommitmentEquivocationError, EffectLeakError, Plan, Vote, CommitmentRound
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Dict, List, Set, Tuple


class CommitmentEquivocationError(RuntimeError):
    """Raised when a round's vote set is not a clean quorum over one digest."""


class EffectLeakError(RuntimeError):
    """Raised when an effect hook fires before full-quorum confirmation."""


@dataclass(frozen=True)
class Plan:
    steps: Tuple[dict, ...]

    def canonical_bytes(self) -> bytes:
        # The ONLY serializer. Every agent hashes these exact bytes.
        # No float normalization, no field dropping, sorted keys only.
        return json.dumps(
            {"steps": list(self.steps)},
            sort_keys=True,
            separators=(",", ":"),
            ensure_ascii=False,
        ).encode("utf-8")

    def digest(self) -> str:
        return hashlib.sha256(self.canonical_bytes()).hexdigest()


@dataclass
class Vote:
    signer: str
    digest: str
    round_id: int


@dataclass
class CommitmentRound:
    round_id: int
    f: int
    votes: List[Vote] = field(default_factory=list)
    effects_fired: Set[str] = field(default_factory=set)

    @property
    def quorum(self) -> int:
        return 2 * self.f + 1

    def add_vote(self, vote: Vote) -> None:
        if vote.round_id != self.round_id:
            raise CommitmentEquivocationError(
                f"vote for round {vote.round_id} injected into round {self.round_id}"
            )
        self.votes.append(vote)

    def finalize(self, plan: Plan) -> str:
        """
        Finalize ONLY if the vote set is a clean quorum over plan.digest(),
        every vote's signer independently re-hashed the same bytes, and no
        signer equivocated across digests within this round.
        """
        expected = plan.digest()

        # (1) equivocation detection: any signer with two digests is Byzantine.
        by_signer: Dict[str, Set[str]] = {}
        for v in self.votes:
            by_signer.setdefault(v.signer, set()).add(v.digest)
        equivocators = {s for s, ds in by_signer.items() if len(ds) > 1}
        if equivocators:
            raise CommitmentEquivocationError(
                f"round {self.round_id}: equivocating signers {sorted(equivocators)} "
                f"voted multiple digests; refusing to finalize"
            )

        # (2) all votes must be over the SAME digest we recomputed from bytes.
        mismatched = [v for v in self.votes if v.digest != expected]
        if mismatched:
            raise CommitmentEquivocationError(
                f"round {self.round_id}: {len(mismatched)} votes over digests "
                f"{sorted({v.digest for v in mismatched})} != recomputed {expected}; "
                f"vote set is split, not a quorum"
            )

        # (3) distinct-identity quorum over that single digest.
        distinct = {v.signer for v in self.votes}
        if len(distinct) < self.quorum:
            raise CommitmentEquivocationError(
                f"round {self.round_id}: only {len(distinct)} distinct signers "
                f"over {expected}, need {self.quorum}"
            )

        # (4) effects may now fire, keyed to the digest.
        self.effects_fired.add(expected)
        return expected

    def fire_effect(self, plan: Plan, step_index: int, confirmed_digest: str) -> None:
        """
        Effect hooks are gated on a confirmed finalization, never on a local
        vote count. This is the guard the P2 leak in the trace lacked.
        """
        if confirmed_digest != plan.digest():
            raise EffectLeakError(
                f"effect for step {step_index} targets digest {plan.digest()} "
                f"but round confirmed {confirmed_digest}"
            )
        if confirmed_digest not in self.effects_fired:
            raise EffectLeakError(
                f"step {step_index} effect fired before quorum finalization "
                f"of {confirmed_digest}; local count is not a commitment"
            )
        # ... execute the effect-fulfilling tool call here ...


def demo() -> None:
    plan_a = Plan(steps=(
        {"tool": "deploy", "args": {"canary": True, "weight": 0.1}},
        {"tool": "verify", "args": {"metric": "err_rate"}},
        {"tool": "promote", "args": {"weight": 1.0}},
    ))
    # A relay that normalizes weight to a string produces a DIFFERENT digest.
    plan_a_prime = Plan(steps=(
        {"tool": "deploy", "args": {"canary": True, "weight": "0.1"}},
        {"tool": "verify", "args": {"metric": "err_rate"}},
        {"tool": "promote", "args": {"weight": 1.0}},
    ))
    assert plan_a.digest() != plan_a_prime.digest()

    rnd = CommitmentRound(round_id=1, f=2)
    # Byzantine B equivocates across both digests.
    rnd.add_vote(Vote("B", plan_a.digest(), 1))
    rnd.add_vote(Vote("B", plan_a_prime.digest(), 1))
    for s in ("A", "C", "D"):
        rnd.add_vote(Vote(s, plan_a.digest(), 1))

    try:
        rnd.finalize(plan_a)
    except CommitmentEquivocationError as e:
        print(f"detected: {e}")

    # And an effect fired on a local view is rejected outright.
    try:
        rnd.fire_effect(plan_a, step_index=2, confirmed_digest=plan_a.digest())
    except EffectLeakError as e:
        print(f"blocked: {e}")


if __name__ == "__main__":
    demo()
