# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-quorum-weight-equivocation-in-federated-agent-consensus-and-why-majority-hash-detection-misses-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-quorum-weight-equivocation-in-federated-agent-consensus-and-why-majority-hash-detection-misses-it.warrant.json
# Markdown SHA-256:   09eb049b7210e36422bd42bfba91fd2002ca2e25b7b058b499db07d2d3426cce
# Code AST SHA-256:   0905a5708c795aca554cc3a22312309cdb524a5b2c40ff3c3436753c384b4bdd
# Verified Classes:   QuorumEquivocationFault, WeightReceipt, WeightMassLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class QuorumEquivocationFault(RuntimeError):
    """Raised when weight-mass skew for a proposal hash exceeds the largest single-org weight."""
    pass


@dataclass
class WeightReceipt:
    peer_id: str
    org_id: str
    org_weight: float
    proposal_hash: str
    epoch: int


@dataclass
class WeightMassLedger:
    # org_id -> weight, fixed per epoch
    weights: Dict[str, float]
    max_network_skew_ms: int = 300
    commit_window_ms: int = 400
    receipts: Dict[str, Dict[str, WeightReceipt]] = field(default_factory=dict)  # hash -> peer -> receipt

    @property
    def w_max(self) -> float:
        return max(self.weights.values()) if self.weights else 0.0

    def record(self, r: WeightReceipt) -> None:
        if r.epoch != self._current_epoch:
            raise QuorumEquivocationFault(
                f"stale-epoch receipt for {r.proposal_hash} from {r.peer_id}"
            )
        self.receipts.setdefault(r.proposal_hash, {})[r.peer_id] = r

    def observed_weight(self, proposal_hash: str, partition: Set[str]) -> float:
        seen = set()
        total = 0.0
        for peer, r in self.receipts.get(proposal_hash, {}).items():
            if r.org_id in partition and r.org_id not in seen:
                seen.add(r.org_id)
                total += r.org_weight
        return total

    def check_equivocation(self, proposal_hash: str, partitions: list[Set[str]]) -> None:
        if self.commit_window_ms < 2 * self.max_network_skew_ms:
            raise QuorumEquivocationFault(
                f"commit window {self.commit_window_ms}ms < 2x skew bound; "
                "late-honest delivery indistinguishable from withholding"
            )
        masses = [self.observed_weight(proposal_hash, p) for p in partitions]
        skew = max(masses) - min(masses)
        if skew > self.w_max:
            raise QuorumEquivocationFault(
                f"structural equivocation on {proposal_hash}: weight-mass skew {skew:.2f} "
                f"> w_max {self.w_max:.2f}; partitions={partitions} masses={masses}"
            )
        if skew > 0.05:
            # suspect selective withholding: force synchronous full-set rebroadcast
            self._force_sync_rebroadcast(proposal_hash)

    def _force_sync_rebroadcast(self, proposal_hash: str) -> None:
        # placeholder: caller must re-broadcast and collect receipts from all peers
        self.receipts.setdefault(proposal_hash, {}).clear()


# --- usage sketch ---
ledger = WeightMassLedger(
    weights={"OrgA": 0.40, "OrgB": 0.25, "OrgC": 0.20, "OrgD": 0.15},
    commit_window_ms=400,
    max_network_skew_ms=300,
)
ledger._current_epoch = 7  # set by epoch manager
for peer, org in [("B1", "OrgB"), ("C1", "OrgC")]:
    ledger.record(WeightReceipt(peer, org, ledger.weights[org], "h", 7))
try:
    ledger.check_equivocation("h", [{"OrgA", "OrgB", "OrgC"}, {"OrgA", "OrgD"}])
except QuorumEquivocationFault as e:
    print("HALT EPOCH:", e)
