# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-slashing-warrant-against-a-reputation-ledger-when-the-byzantine-quorum-that-issued-it-has-since-equivocated.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-slashing-warrant-against-a-reputation-ledger-when-the-byzantine-quorum-that-issued-it-has-since-equivocated.warrant.json
# Markdown SHA-256:   8e6481b695c4d8ec5d29ab8d2e8302f426acf506838ac9ef58fd8ec6a41511f4
# Code AST SHA-256:   ddc57e3d0b87360d73eab14523aec368e24dce56b5dff65b0d087b595945d2f9
# Verified Classes:   ReputationWarrantError, Warrant, ReputationLedger
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, FrozenSet, List, Optional, Set, Tuple


class ReputationWarrantError(RuntimeError):
    """Raised when a reputation delta cannot be soundly applied or resolved."""
    pass


@dataclass(frozen=True)
class Warrant:
    target: str
    delta: int
    view: int
    signers: FrozenSet[str]


@dataclass
class ReputationLedger:
    quorum_size: int
    highest_observed_view: int = 0
    # target -> accumulated reputation
    balances: Dict[str, int] = field(default_factory=dict)
    # signer -> set of views in which it equivocated (signed conflicting artifacts)
    equivocation_views: Dict[str, Set[int]] = field(default_factory=dict)
    # deferred warrants awaiting equivocation resolution
    pending: List[Warrant] = field(default_factory=list)

    def observe_view(self, view: int) -> None:
        if view > self.highest_observed_view:
            self.highest_observed_view = view

    def record_equivocation(self, signer: str, view: int) -> None:
        self.equivocation_views.setdefault(signer, set()).add(view)

    def _signer_trustworthy_at(self, signer: str, up_to_view: int) -> bool:
        # A signer is untrustworthy for any warrant whose view is at or below
        # a view in which it was observed equivocating.
        return not any(v <= up_to_view for v in self.equivocation_views.get(signer, set()))

    def _is_valid_quorum(self, signers: FrozenSet[str]) -> bool:
        return len(signers) >= self.quorum_size

    def apply_warrant(self, w: Warrant) -> str:
        """Returns 'applied', 'deferred', or raises ReputationWarrantError."""
        self.observe_view(w.view)

        if not self._is_valid_quorum(w.signers):
            raise ReputationWarrantError(
                f"warrant for {w.target} at view {w.view} carries "
                f"{len(w.signers)} signatures, below quorum {self.quorum_size}"
            )

        # Boundary check: are any signers implicated in equivocation at or
        # below the highest view this instance has observed?
        implicated = {
            s for s in w.signers
            if not self._signer_trustworthy_at(s, self.highest_observed_view)
        }

        if implicated:
            # Defer, do not apply and do not discard.
            self.pending.append(w)
            return "deferred"

        self.balances[w.target] = self.balances.get(w.target, 0) + w.delta
        return "applied"

    def resolve_pending(self) -> Tuple[List[Warrant], List[Warrant]]:
        """Re-evaluate deferred warrants against current equivocation state.
        Returns (applied, rejected)."""
        applied: List[Warrant] = []
        rejected: List[Warrant] = []
        still_pending: List[Warrant] = []

        for w in self.pending:
            implicated = {
                s for s in w.signers
                if not self._signer_trustworthy_at(s, self.highest_observed_view)
            }
            if not implicated:
                self.balances[w.target] = self.balances.get(w.target, 0) + w.delta
                applied.append(w)
            elif len(w.signers - implicated) < self.quorum_size:
                # Signer set can no longer form a quorum without the equivocators.
                rejected.append(w)
            else:
                still_pending.append(w)

        self.pending = still_pending
        return applied, rejected


def apply_warrant_or_fail(ledger: ReputationLedger, w: Warrant) -> str:
    """Operational entry point: apply, or raise on an unsound warrant."""
    if w.delta > 0:
        # Credits follow the same rule; do not special-case.
        pass
    try:
        return ledger.apply_warrant(w)
    except ReputationWarrantError:
        raise
    except Exception as exc:  # noqa: BLE001
        raise ReputationWarrantError(
            f"unexpected failure applying warrant for {w.target} at view {w.view}: {exc}"
        ) from exc


# --- Reproduction of the observed trace ---
if __name__ == "__main__":
    ledger = ReputationLedger(quorum_size=5)
    ledger.balances.update({"A": 100, "B": 100})

    w1 = Warrant("A", -40, 100, frozenset({"V1", "V2", "V3", "V4", "V5"}))
    w2 = Warrant("B", -40, 101, frozenset({"V1", "V2", "V3", "V4", "V6"}))

    # I9 applies W1 naively (no equivocation known yet).
    assert apply_warrant_or_fail(ledger, w1) == "applied"

    # Honest view-103 quorum advances; I9 observes it.
    ledger.observe_view(103)

    # I9 now learns V3 and V4 equivocated at views 100 and 101.
    ledger.record_equivocation("V3", 100)
    ledger.record_equivocation("V4", 100)
    ledger.record_equivocation("V3", 101)
    ledger.record_equivocation("V4", 101)

    # W2 now hits the boundary: V3,V4 are implicated -> deferred.
    assert apply_warrant_or_fail(ledger, w2) == "deferred"

    applied, rejected = ledger.resolve_pending()

    # The naive implementation would have slashed B to 60.
    # The corrected implementation refuses to apply W2.
    assert ledger.balances["B"] == 100, ledger.balances
    assert len(rejected) == 1 and rejected[0].target == "B"

    # W1 remains applied (it predated observation of equivocation and was not
    # contradicted by a higher-view honest quorum). A compensating credit
    # warrant would be required to reverse it, itself subject to this rule.
    assert ledger.balances["A"] == 60
    print("ledger converged:", ledger.balances)
