# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-equivocation-detection-when-bft-quorum-certificates-are-signed-over-divergent-task-decompositions.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-equivocation-detection-when-bft-quorum-certificates-are-signed-over-divergent-task-decompositions.warrant.json
# Markdown SHA-256:   193364e61eecf17347119811f4c039f912dcc6a77fd9615d7f697b16e8b13076
# Code AST SHA-256:   905691f6f94aa1365e2c575ad19f36169f693418014dea43557cab1698cdda6d
# Verified Classes:   EquivocationBoundaryError, Proposal, CommitmentTracker
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class EquivocationBoundaryError(RuntimeError):
    """Raised when a signer's fault is misclassified at the decomposition boundary."""
    pass


@dataclass(frozen=True)
class Proposal:
    parent_hash: str
    sub_dag_hash: str
    signer: str
    payload: bytes


@dataclass
class CommitmentTracker:
    # (parent, sub_dag_hash, signer) -> payload, for genuine-equivocation detection
    signed: Dict[Tuple[str, str, str], bytes] = field(default_factory=dict)
    # parent -> {signer -> sub_dag_hash}, for at-most-once-per-parent enforcement
    per_parent: Dict[str, Dict[str, str]] = field(default_factory=dict)

    def observe(self, p: Proposal) -> str:
        key = (p.parent_hash, p.sub_dag_hash, p.signer)
        if key in self.signed and self.signed[key] != p.payload:
            # Same content-addressed slot, contradictory payload: provably Byzantine.
            raise EquivocationBoundaryError(
                f"genuine equivocation by {p.signer} on {p.sub_dag_hash}"
            )
        self.signed[key] = p.payload

        seen = self.per_parent.setdefault(p.parent_hash, {})
        prior = seen.get(p.signer)
        if prior is not None and prior != p.sub_dag_hash:
            # Soft fault: signer hedged across decompositions. Discard, do not slash.
            return "HEDGE_DISCARDED"
        seen[p.signer] = p.sub_dag_hash
        return "COUNTED"

    def quorum(self, parent_hash: str, sub_dag_hash: str, threshold: int) -> bool:
        # Count distinct signers per sub_dag_hash, capped at one per parent.
        eligible = {
            s for s, h in self.per_parent.get(parent_hash, {}).items()
            if h == sub_dag_hash
        }
        return len(eligible) >= threshold
