# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-plan-quorum-it-cannot-re-derive-silent-equivocation-in-bft-plan-commitment-under-hallucinating-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-plan-quorum-it-cannot-re-derive-silent-equivocation-in-bft-plan-commitment-under-hallucinating-agents.warrant.json
# Markdown SHA-256:   67480b592ecb3900b4e8628c72506ae7468e30bb850603262863c8fec56b5bb2
# Code AST SHA-256:   aa4287ece5293e4aa136af17e77fba24abdb145666031175754bfb259e5e9aef
# Verified Classes:   DerivationDivergenceError, PlanCommit
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DerivationDivergenceError(RuntimeError):
    """Raised when an executor re-derives a plan that does not match the committed preimage.

    This is a consensus-layer fault, not a transient error: the executor is a fresh
    replica whose sample diverged from the committed point. Retrying masks it.
    """
    pass


@dataclass(frozen=True)
class PlanCommit:
    plan_text: str          # full preimage, not a hash
    committed_hash: str
    quorum: int


def commit_plan(replica_outputs: list[str], quorum: int) -> PlanCommit:
    """Commit the modal plan preimage. Requires the preimage, not just a hash."""
    if len(replica_outputs) < quorum:
        raise DerivationDivergenceError(
            f"insufficient replicas: {len(replica_outputs)} < quorum {quorum}"
        )
    counts: dict[str, int] = {}
    for out in replica_outputs:
        counts[out] = counts.get(out, 0) + 1
    modal, n = max(counts.items(), key=lambda kv: kv[1])
    if n < quorum:
        raise DerivationDivergenceError(
            f"no preimage reached quorum: max support {n} < {quorum}; "
            f"divergent samplers consumed fault budget"
        )
    return PlanCommit(modal, hashlib.sha256(modal.encode()).hexdigest(), quorum)


def execute_committed(commit: PlanCommit, executor_rederive) -> str:
    """Execute the committed preimage. Re-derivation is a hard check, never a retry."""
    derived = executor_rederive(commit.plan_text)
    derived_hash = hashlib.sha256(derived.encode()).hexdigest()
    if derived_hash != commit.committed_hash:
        raise DerivationDivergenceError(
            f"executor re-derivation diverged from commit: "
            f"{derived_hash[:12]} != {commit.committed_hash[:12]}; "
            f"escalate to new consensus round, do not retry"
        )
    return commit.plan_text
