# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-peer-reputation-attestation-whose-slashable-bond-was-already-burned-by-a-concurrent-auditor.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-peer-reputation-attestation-whose-slashable-bond-was-already-burned-by-a-concurrent-auditor.warrant.json
# Markdown SHA-256:   700d34bef307eabfdefa66ef55fd0e300f8ef505de49e69f25306cc35b3cb4f0
# Code AST SHA-256:   ea910b3a8cfa5fab778447dfac4d920c3eb5d3419662229cdd0334cf038fb05b
# Verified Classes:   ReputationAttestationError, Attestation, SubjectEvent, ReputationLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ReputationAttestationError(RuntimeError):
    """Raised when a reputation attestation cannot be safely applied."""
    pass


@dataclass
class Attestation:
    subject_id: str
    task_id: str
    fault_class: str
    auditor_id: str
    bond_ref_epoch: int
    requested_slash: int


@dataclass
class SubjectEvent:
    slashed_total: int = 0
    last_mutation_epoch: int = -1
    auditor_set: Set[str] = field(default_factory=set)
    corroboration_count: int = 0


class ReputationLedger:
    """
    Enforces the invariant: reputation deltas are a function of distinct
    (subject, task, fault_class) events, weighted by independent auditor
    corroboration, and clamped by remaining slashable stake at the
    attestation's bond_ref epoch.
    """

    PER_ATTESTATION_CAP = 200

    def __init__(self, bonds: Dict[str, int]):
        self._bonds = dict(bonds)
        self._events: Dict[Tuple[str, str, str], SubjectEvent] = {}

    def _key(self, a: Attestation) -> Tuple[str, str, str]:
        return (a.subject_id, a.task_id, a.fault_class)

    def apply(self, a: Attestation) -> str:
        key = self._key(a)
        ev = self._events.get(key)

        # Epoch monotonicity: an attestation reasoning about a bond state
        # that has already been mutated for this key is quarantined.
        if ev is not None and a.bond_ref_epoch < ev.last_mutation_epoch:
            return "quarantined:stale_bond_ref"

        # Duplicate auditor for the same key: possible replay/equivocation.
        if ev is not None and a.auditor_id in ev.auditor_set:
            return "quarantined:duplicate_auditor"

        if ev is None:
            ev = SubjectEvent()
            self._events[key] = ev

        if a.auditor_id in ev.auditor_set:
            raise ReputationAttestationError(
                f"auditor {a.auditor_id} already recorded for key {key}"
            )

        # Clamp by remaining stake at this epoch.
        remaining = self._bonds.get(a.subject_id, 0)
        honored = min(a.requested_slash, self.PER_ATTESTATION_CAP, remaining)
        if honored < a.requested_slash and ev.slashed_total == 0:
            # First slash on this key could not be fully honored: the bond
            # was already depleted by an unrelated fault. Surface it rather
            # than silently rejecting, so consumers do not credit the subject.
            ev.auditor_set.add(a.auditor_id)
            ev.slashed_total += honored
            ev.last_mutation_epoch = max(ev.last_mutation_epoch, a.bond_ref_epoch)
            self._bonds[a.subject_id] = remaining - honored
            raise ReputationAttestationError(
                f"partial_slash: honored {honored}/{a.requested_slash} "
                f"for {a.subject_id} on {key}; shortfall recorded"
            )

        ev.auditor_set.add(a.auditor_id)
        ev.slashed_total += honored
        ev.corroboration_count += 1
        ev.last_mutation_epoch = max(ev.last_mutation_epoch, a.bond_ref_epoch)
        self._bonds[a.subject_id] = remaining - honored

        if ev.corroboration_count == 1:
            return "accepted:primary"
        return f"accepted:corroboration(c={ev.corroboration_count})"

    def reputation_delta(self, subject_id: str, task_id: str, fault_class: str) -> float:
        """Bounded corroboration weighting; never sum of attestations."""
        ev = self._events.get((subject_id, task_id, fault_class))
        if ev is None:
            return 0.0
        import math
        w = 1.0 + math.log1p(ev.corroboration_count - 1)
        return ev.slashed_total * w
