# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-quorum-certified-plan-replay-from-accepting-a-byzantine-proposer-s-divergent-sub-plan-under-partial-participant-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-quorum-certified-plan-replay-from-accepting-a-byzantine-proposer-s-divergent-sub-plan-under-partial-participant-failure.warrant.json
# Markdown SHA-256:   4b8b0b8d6ffee49f0dd3504c5c615a89cccec1ce3201ee63c257b639721c6ad2
# Code AST SHA-256:   801d31f198543efc295646872342191ef6bde5e3c30f551fc84872f3bc60387a
# Verified Classes:   UncertifiablePlanError, SubPlan, Plan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from typing import Iterable


class UncertifiablePlanError(RuntimeError):
    """Raised when a plan's composition graph is not order-invariant over
    shared mutable state, so no quorum over its execution digest is sound."""


@dataclass(frozen=True)
class SubPlan:
    sid: str
    mutates: frozenset[str] = frozenset()
    reads: frozenset[str] = frozenset()


@dataclass
class Plan:
    subplans: list[SubPlan]
    edges: set[tuple[str, str]] = field(default_factory=set)  # (before, after)
    commutativity_witness: set[frozenset[str]] = field(default_factory=set)


def _touches_shared(a: SubPlan, b: SubPlan) -> bool:
    shared = (a.mutates & b.mutates) | (a.mutates & b.reads) | (b.mutates & a.reads)
    return bool(shared)


def certify_determinism(plan: Plan) -> None:
    """Enforce determinism-before-quorum. Raises if any pair of sub-plans that
    touches shared mutable state lacks both a dependency edge and a
    commutativity witness. A vote cast on such a plan is unsound."""
    by_id = {s.sid: s for s in plan.subplans}
    ordered = plan.edges | {(b, a) for (a, b) in plan.edges}
    for i, a in enumerate(plan.subplans):
        for b in plan.subplans[i + 1:]:
            if not _touches_shared(a, b):
                continue
            has_edge = (a.sid, b.sid) in ordered
            has_witness = frozenset({a.sid, b.sid}) in plan.commutativity_witness
            if not (has_edge or has_witness):
                raise UncertifiablePlanError(
                    f"sub-plans {a.sid!r} and {b.sid!r} share mutable state "
                    f"({sorted((a.mutates | b.mutates) & (a.reads | b.reads | a.mutates | b.mutates))}) "
                    f"with no dependency edge and no commutativity witness; "
                    f"execution order is nondeterministic and any QC over the "
                    f"resulting digest is unsound under partial Byzantine failure."
                )


def collect_votes(plan: Plan, votes: Iterable[tuple[str, bytes]], quorum: int) -> bytes:
    """Gate vote collection on determinism certification. Votes on an
    uncertifiable plan are rejected structurally, before any quorum math."""
    certify_determinism(plan)
    tally: dict[bytes, int] = {}
    for _voter, digest in votes:
        tally[digest] = tally.get(digest, 0) + 1
    winner, count = max(tally.items(), key=lambda kv: kv[1])
    if count < quorum:
        raise UncertifiablePlanError(f"no quorum: max {count} < required {quorum}")
    if len(tally) > 1:
        # With a determinism witness in hand, divergence is now a genuine
        # Byzantine/crash signal, not a plan-construction ambiguity.
        raise UncertifiablePlanError(
            f"digest divergence on witnessed-deterministic plan: {dict(tally)}"
        )
    return winner
