# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-fault-tolerant-agent-swarm-commit-to-a-task-that-no-quorum-ever-authorized-and-how-does-the-equivocation-witness-i.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-fault-tolerant-agent-swarm-commit-to-a-task-that-no-quorum-ever-authorized-and-how-does-the-equivocation-witness-i.warrant.json
# Markdown SHA-256:   91ad38f444aa741c566c9f951c05df2ec2b1d7b84a5e38d248cdbec1675611b2
# Code AST SHA-256:   41d4d6a3136eae5d1c84891ee287f10da6321f4414c9293308f82d9521133bc3
# Verified Classes:   InterpretationDivergenceError, Proposal, Vote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class InterpretationDivergenceError(RuntimeError):
    """Raised when a quorum signs byte-identical proposals but canonical
    action digests diverge. This is NOT Byzantine equivocation and must
    NOT trigger a view change; it must abort the round and name the
    under-specified term."""
    pass


@dataclass
class Proposal:
    raw: str
    under_specified_terms: list[str] = field(default_factory=list)


@dataclass
class Vote:
    replica_id: int
    proposal_digest: str          # hash of raw proposal bytes
    action_digest: str            # hash of canonical interpreted action
    canonical_action: dict[str, Any]


def canonicalize(proposal: Proposal, replica_id: int, local_context: dict) -> dict:
    """Deterministic interpretation. In a correct implementation this MUST
    be identical across replicas; here we simulate replica-local drift to
    show the failure. A real guardrail replaces this with a typed parser
    whose output is independent of replica-local context."""
    action: dict[str, Any] = {"op": "reconcile"}
    for term in proposal.under_specified_terms:
        # Replica-local resolution: the exact bug. 'provenance >= 12' resolves
        # differently depending on what the replica's context happens to hold.
        if term == "provenance >= 12":
            if "timestamp_epoch" in local_context:
                action["provenance_filter"] = ("timestamp", 12)
            elif "entry_index" in local_context:
                action["provenance_filter"] = ("index", 12)
            else:
                action["provenance_filter"] = ("chain_lookup", 12)
        elif term == "superseded by checkpoint 44":
            action["supersession"] = local_context.get("chain_mode", "drop")
    return action


def digest(obj: Any) -> str:
    return hashlib.sha256(
        json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()


def run_round(proposal: Proposal, replicas: dict[int, dict], quorum: int) -> Vote:
    votes: list[Vote] = []
    for rid, ctx in replicas.items():
        action = canonicalize(proposal, rid, ctx)
        votes.append(Vote(
            replica_id=rid,
            proposal_digest=digest(proposal.raw),
            action_digest=digest(action),
            canonical_action=action,
        ))

    # Classical BFT check: all proposal digests identical -> no equivocation.
    proposal_digests = {v.proposal_digest for v in votes}
    assert len(proposal_digests) == 1, "leader equivocation detected"

    # The missing invariant: quorum must agree on ACTION digest, not just
    # proposal digest. Without this, the round commits semantic divergence.
    action_digests = {v.action_digest for v in votes}
    if len(action_digests) > 1:
        divergent_terms = sorted({
            term for term in proposal.under_specified_terms
            if any(
                canonicalize(proposal, v.replica_id, replicas[v.replica_id]).get(term)
                != canonicalize(proposal, votes[0].replica_id, replicas[votes[0].replica_id]).get(term)
                for v in votes
            )
        })
        raise InterpretationDivergenceError(
            f"quorum reached on proposal bytes ({len(votes)} votes) but "
            f"{len(action_digests)} distinct action digests; "
            f"under-specified terms causing divergence: {divergent_terms}. "
            f"Abort round; do NOT view-change (re-proposal will re-diverge)."
        )

    if len(votes) < quorum:
        raise InterpretationDivergenceError(
            f"quorum not reached: {len(votes)} < {quorum}"
        )
    return votes[0]


if __name__ == "__main__":
    proposal = Proposal(
        raw="reconcile: drop entries superseded by checkpoint 44, "
            "retain entries with provenance >= 12",
        under_specified_terms=["provenance >= 12", "superseded by checkpoint 44"],
    )
    replicas = {
        1: {"entry_index": True},
        2: {"timestamp_epoch": True},
        3: {"chain_mode": "drop"},
        4: {"entry_index": True},
        5: {"entry_index": True},
        6: {"timestamp_epoch": True},
        7: {"chain_mode": "drop"},
    }
    try:
        run_round(proposal, replicas, quorum=5)
    except InterpretationDivergenceError as e:
        print(f"ROUND ABORTED: {e}")
