# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-quarantine-a-peer-s-signed-verdict-when-trust-tier-weight-vectors-diverge-mid-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-quarantine-a-peer-s-signed-verdict-when-trust-tier-weight-vectors-diverge-mid-consensus.warrant.json
# Markdown SHA-256:   2eae3931eb965e4bca3ac0d5ed3ac0aa84811d7446c53984b15a8b40f90ebb2b
# Code AST SHA-256:   38c084ce3c36db38a8bb3c6b2cc27dd4b4ce00a3311f3c8a3fd8de3cd8b45335
# Verified Classes:   WeightInstabilityError, Verdict, RoundState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class WeightInstabilityError(RuntimeError):
    """Raised when a peer's verdict would be tallied under a weight that
    differs from the weight it was scored against at receipt time."""
    pass


@dataclass
class Verdict:
    peer_id: str
    round_id: str
    accept: bool
    scored_weight_at_receipt: float
    signature_valid: bool


@dataclass
class RoundState:
    round_id: str
    quorum_threshold: float
    frozen_weights: Dict[str, float] = field(default_factory=dict)
    verdicts: Dict[str, Verdict] = field(default_factory=dict)
    status: str = "open"  # open | weight-unstable | committed


def tally_verdict(
    state: RoundState,
    verdict: Verdict,
    current_trust_table: Dict[str, float],
) -> Optional[bool]:
    """Attempt to fold a verdict into the round tally.

    Returns True/False if quorum is decided, None if still open.
    Raises WeightInstabilityError if the local trust table diverged from
    the weight the verdict was scored against at receipt.
    """
    if state.status == "committed":
        raise WeightInstabilityError(
            f"round {state.round_id} already committed; refusing late verdict"
        )

    if not verdict.signature_valid:
        # Invalid signatures are dropped, not quarantined.
        return None

    current_weight = current_trust_table.get(verdict.peer_id)
    if current_weight is None:
        raise WeightInstabilityError(
            f"peer {verdict.peer_id} absent from trust table mid-round"
        )

    # THE INVARIANT: weight applied at tally must equal weight at receipt.
    if abs(current_weight - verdict.scored_weight_at_receipt) > 1e-9:
        state.status = "weight-unstable"
        raise WeightInstabilityError(
            f"peer {verdict.peer_id} weight drifted "
            f"{verdict.scored_weight_at_receipt} -> {current_weight} "
            f"within round {state.round_id}; quarantine and reconcile"
        )

    state.verdicts[verdict.peer_id] = verdict
    total = sum(v.scored_weight_at_receipt for v in state.verdicts.values() if v.accept)

    if total >= state.quorum_threshold:
        state.status = "committed"
        return True
    return None


def demote_peer(
    state: RoundState,
    trust_table: Dict[str, float],
    peer_id: str,
    new_weight: float,
) -> None:
    """Apply a local demotion. Must NOT retroactively re-score in-flight rounds."""
    if any(v.peer_id == peer_id for v in state.verdicts.values()):
        # A verdict from this peer is already in the open round; the
        # demotion is valid but must be deferred to the next round.
        trust_table[peer_id] = new_weight
        state.status = "weight-unstable"
        raise WeightInstabilityError(
            f"cannot demote {peer_id} while its verdict is in open round "
            f"{state.round_id}; demotion deferred, round frozen"
        )
    trust_table[peer_id] = new_weight
