# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-reputation-ledger-equivocation-when-federated-auditors-disagree-under-sybil-weighted-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-reputation-ledger-equivocation-when-federated-auditors-disagree-under-sybil-weighted-quorum.warrant.json
# Markdown SHA-256:   e65009a86e6a0e0c01f142eb83b604b045c4dd68ffd0e87d06a41fc7d6f08f36
# Code AST SHA-256:   799501154eb2a4b02254ac6a70b176b43a53b2e2ecf2d634fe31880bfc3a4991
# Verified Classes:   LedgerEquivocation, SybilSuspectDelta, Delta
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class LedgerEquivocation(RuntimeError):
    """Raised when two deltas for the same (subject, epoch) both clear quorum."""
    pass


class SybilSuspectDelta(RuntimeError):
    """Raised when provenance dedup collapses a delta's quorum mass below threshold."""
    pass


@dataclass(frozen=True)
class Delta:
    subject: str
    epoch: int
    value: float
    auditors: Mapping[str, str]  # auditor_id -> provenance_root
    trust_mass: Mapping[str, float]  # auditor_id -> mass


def dedup_mass(delta: Delta, per_root_cap: int = 1) -> float:
    """Sum trust mass over distinct provenance roots, capping auditors per root."""
    by_root: dict[str, list[float]] = {}
    for auditor, root in delta.auditors.items():
        by_root.setdefault(root, []).append(delta.trust_mass[auditor])
    total = 0.0
    for root, masses in by_root.items():
        masses.sort(reverse=True)
        total += sum(masses[:per_root_cap])
    return total


def certify(
    deltas: list[Delta],
    total_mass: float,
    q: float = 0.66,
    amplification_limit: float = 1.5,
) -> Delta:
    """Return the single quorum-certified delta, or raise on equivocation/Sybil."""
    if not deltas:
        raise LedgerEquivocation("no deltas submitted for certification")

    certified: list[Delta] = []
    for d in deltas:
        raw = sum(d.trust_mass[a] for a in d.auditors)
        dedup = dedup_mass(d)
        if raw / max(dedup, 1e-9) > amplification_limit:
            raise SybilSuspectDelta(
                f"delta {d.subject}@{d.epoch} amplification "
                f"{raw / dedup:.2f} exceeds {amplification_limit}"
            )
        if dedup / total_mass > q:
            certified.append(d)

    if len(certified) > 1:
        heads = [(d.value, dedup_mass(d)) for d in certified]
        raise LedgerEquivocation(
            f"equivocated heads for {certified[0].subject}@{certified[0].epoch}: {heads}"
        )
    if not certified:
        raise SybilSuspectDelta(
            f"no delta for {deltas[0].subject}@{deltas[0].epoch} clears "
            f"provenance-deduplicated quorum {q}"
        )
    return certified[0]
