# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-equivocate-undetected-when-its-quorum-certificate-is-re-signed-under-a-rotated-agent-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-equivocate-undetected-when-its-quorum-certificate-is-re-signed-under-a-rotated-agent-identity.warrant.json
# Markdown SHA-256:   b5c0938dd9b9655f2fcf43373e9e2f0fc6804adfce6a898c5eea1653200014f4
# Code AST SHA-256:   99b62d7db9466b11a8cf0d3de2ab4b90db5a2d7b58900ffd0c843dd1bd698326
# Verified Classes:   EquivocationBlindSpot, RotationWarrant, SignedProposal, EvidenceStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EquivocationBlindSpot(RuntimeError):
    """Raised when a logical agent's key lineage allows undetected equivocation."""
    pass


@dataclass
class RotationWarrant:
    old_key: str
    new_key: str
    epoch: int
    view_range: tuple[int, int]
    sig_by_old: str  # signature of (old,new,epoch,range) under old_key


@dataclass
class SignedProposal:
    logical_id: str
    leaf_key: str
    view: int
    block_hash: str
    sig: str


@dataclass
class EvidenceStore:
    warrants: list[RotationWarrant] = field(default_factory=list)
    proposals: list[SignedProposal] = field(default_factory=list)

    def lineage(self, leaf_key: str) -> set[str]:
        """Expand a leaf key to its full rotation lineage (both directions)."""
        keys = {leaf_key}
        changed = True
        while changed:
            changed = False
            for w in self.warrants:
                if w.old_key in keys and w.new_key not in keys:
                    keys.add(w.new_key)
                    changed = True
                if w.new_key in keys and w.old_key not in keys:
                    keys.add(w.old_key)
                    changed = True
        return keys

    def detect_equivocation(self) -> Optional[tuple[str, int, str, str]]:
        """Group by LOGICAL identity via lineage, not by leaf key."""
        by_logical: dict[tuple[str, int], dict[str, str]] = {}
        for p in self.proposals:
            key = (p.logical_id, p.view)
            by_logical.setdefault(key, {})
            prev = by_logical[key].get(p.leaf_key)
            if prev is not None and prev != p.block_hash:
                return (p.logical_id, p.view, prev, p.block_hash)
            by_logical[key][p.leaf_key] = p.block_hash

        # Cross-key equivocation: same logical id, same view, different leaf keys,
        # different blocks, and both keys fall in one lineage.
        for (logical_id, view), keyed in by_logical.items():
            if len(keyed) < 2:
                continue
            leaves = list(keyed.keys())
            for i in range(len(leaves)):
                for j in range(i + 1, len(leaves)):
                    k1, k2 = leaves[i], leaves[j]
                    if keyed[k1] == keyed[k2]:
                        continue
                    if k2 in self.lineage(k1):
                        return (logical_id, view, keyed[k1], keyed[k2])
        return None

    def assert_no_blind_spot(self, logical_id: str, view: int) -> None:
        """Guard called before accepting a QC at (logical_id, view)."""
        conflicting = [
            p for p in self.proposals
            if p.logical_id == logical_id and p.view == view
        ]
        blocks = {p.block_hash for p in conflicting}
        if len(blocks) > 1:
            raise EquivocationBlindSpot(
                f"logical agent {logical_id} has conflicting proposals at view "
                f"{view}: {sorted(blocks)}; QC must be rejected"
            )


def accept_qc(store: EvidenceStore, logical_id: str, view: int,
              block_hash: str, leaf_key: str) -> None:
    # Durability: the proposed-in-view fact is written BEFORE the QC is honored.
    store.proposals.append(
        SignedProposal(logical_id, leaf_key, view, block_hash, sig="<sig>")
    )
    try:
        store.assert_no_blind_spot(logical_id, view)
    except EquivocationBlindSpot:
        raise
    ev = store.detect_equivocation()
    if ev is not None:
        raise EquivocationBlindSpot(
            f"slashable equivocation by {ev[0]} at view {ev[1]}: "
            f"{ev[2]} vs {ev[3]} across key lineage"
        )


if __name__ == "__main__":
    store = EvidenceStore()
    store.warrants.append(
        RotationWarrant("k_a1", "k_a2", epoch=1, view_range=(0, 20),
                        sig_by_old="<sig>")
    )
    # P1 under k_a1 at view 12, then resumed instance P2 under k_a2 at view 12.
    accept_qc(store, "planner-07", 12, "P1", "k_a1")
    accept_qc(store, "planner-07", 12, "P2", "k_a2")  # must raise
