# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-vote-weight-drifts-after-a-partial-view-change-in-heterogeneous-bft-orchestrator-swarms.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-vote-weight-drifts-after-a-partial-view-change-in-heterogeneous-bft-orchestrator-swarms.warrant.json
# Markdown SHA-256:   3dccdb4f7cf0f8e68bac59f4950443d086efec6324d68398666b6d5a59601f12
# Code AST SHA-256:   7888f113ee0268a3f89ab7e02de318b4eea5ca11a1790543377b8fa6dde842bb
# Verified Classes:   WeightEpochDriftError, WeightSnapshot, ViewChange, NewView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class WeightEpochDriftError(RuntimeError):
    """Raised when a consensus certificate references a weight vector that
    does not match the epoch pinned at view-change time. This is a *malformed
    certificate*, distinct from an insufficient-quorum rejection—conflating the
    two is what made the original failure undiagnosable."""
    pass


@dataclass(frozen=True)
class WeightSnapshot:
    epoch: int
    weights: dict  # node_id -> int
    vector_hash: str = field(init=False)

    def __post_init__(self):
        blob = repr(sorted(self.weights.items())).encode()
        object.__setattr__(self, "vector_hash", hashlib.sha256(blob).hexdigest()[:16])

    def quorum_weight(self) -> int:
        return (sum(self.weights.values()) * 2) // 3 + 1


@dataclass
class ViewChange:
    view: int
    node_id: str
    weight_epoch: int
    vector_hash: str


@dataclass
class NewView:
    view: int
    weight_epoch: int
    vector_hash: str
    votes: list  # list[ViewChange]


def validate_new_view(nv: NewView, pinned: WeightSnapshot) -> None:
    """Validate a NEW-VIEW certificate against the epoch snapshot pinned at
    view-change start. Rejects on epoch/hash mismatch BEFORE quorum math."""
    if nv.weight_epoch != pinned.epoch:
        raise WeightEpochDriftError(
            f"NEW-VIEW view={nv.view} cites weight_epoch={nv.weight_epoch} "
            f"but view change pinned epoch={pinned.epoch}"
        )
    if nv.vector_hash != pinned.vector_hash:
        raise WeightEpochDriftError(
            f"NEW-VIEW view={nv.view} vector_hash={nv.vector_hash} != "
            f"pinned {pinned.vector_hash} (live weights leaked into certificate)"
        )
    for vc in nv.votes:
        if vc.weight_epoch != pinned.epoch or vc.vector_hash != pinned.vector_hash:
            raise WeightEpochDriftError(
                f"VIEW-CHANGE from {vc.node_id} carries epoch={vc.weight_epoch} "
                f"hash={vc.vector_hash}, inconsistent with pinned epoch"
            )
    # Only after epoch consistency is proven do we check quorum weight.
    cast_weight = sum(pinned.weights.get(vc.node_id, 0) for vc in nv.votes)
    if cast_weight < pinned.quorum_weight():
        raise WeightEpochDriftError(
            f"NEW-VIEW view={nv.view} cast_weight={cast_weight} < "
            f"quorum={pinned.quorum_weight()} under pinned epoch {pinned.epoch}"
        )


def run_view_change(pinned: WeightSnapshot, incoming: list) -> NewView:
    """Simulates a view change where a competence scorer fires mid-transition.
    The pinned snapshot must dominate; any live-weight leakage is fatal."""
    nv = NewView(
        view=pinned.epoch + 1,
        weight_epoch=pinned.epoch,
        vector_hash=pinned.vector_hash,
        votes=incoming,
    )
    validate_new_view(nv, pinned)
    return nv


if __name__ == "__main__":
    pinned = WeightSnapshot(epoch=7, weights={"O1": 2, "O2": 2, "O3": 2,
                                              "O4": 1, "O5": 1, "O6": 1, "O7": 1})
    # Honest votes cast under the pinned epoch.
    honest = [ViewChange(8, n, 7, pinned.vector_hash) for n in
              ("O1", "O2", "O3", "O4", "O5")]
    run_view_change(pinned, honest)  # OK: 8/10 weight >= quorum 7

    # A replica that re-read live scores after O3 dropped 2->1 leaks a new hash.
    drifted = honest + [ViewChange(8, "O6", 7, "deadbeefdeadbeef")]
    try:
        run_view_change(pinned, drifted)
    except WeightEpochDriftError as e:
        print(f"BLOCKED: {e}")
