# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-on-quorum-evidence-that-is-internally-consistent-but-causally-impossible.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-on-quorum-evidence-that-is-internally-consistent-but-causally-impossible.warrant.json
# Markdown SHA-256:   82e2ef2a80727491445664373630d6a80ca2fa3d918d01a9b0c11d09e6ad8093
# Code AST SHA-256:   10bb10ec1409c0686e5fe621c8f6214c0f9102adc4bca8bab43198c8260e3226
# Verified Classes:   CausallyImpossibleQuorum, Vote, QuorumCertificate, DurableIdentity
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Iterable


class CausallyImpossibleQuorum(RuntimeError):
    """Raised when a quorum certificate is signature-valid but could not
    have been produced by the claimed signers in a consistent history."""


@dataclass(frozen=True)
class Vote:
    signer: str
    view: int
    index: int
    parent_digest: str          # digest of committed state at index-1
    signature: str              # assumed verified upstream


@dataclass(frozen=True)
class QuorumCertificate:
    index: int
    votes: tuple[Vote, ...]
    threshold: int


@dataclass(frozen=True)
class DurableIdentity:
    """Lives OUTSIDE checkpointable execution state. Never rewound."""
    agent_id: str
    view_high_water: int


def _digest(v: Vote) -> str:
    return hashlib.sha256(
        f"{v.signer}|{v.view}|{v.index}|{v.parent_digest}".encode()
    ).hexdigest()


def assert_quorum_feasible(
    qc: QuorumCertificate,
    identity: DurableIdentity,
    peer_high_water: dict[str, int],
    sibling_qc: QuorumCertificate | None = None,
) -> None:
    """Enforce the feasibility predicate before committing.

    Counting is necessary, not sufficient. This checks that the quorum
    could actually have been cast given durable view state and causal
    ordering, and rejects internally-consistent-but-impossible bundles.
    """
    if len(qc.votes) < qc.threshold:
        raise CausallyImpossibleQuorum(
            f"index {qc.index}: only {len(qc.votes)} votes, "
            f"threshold {qc.threshold}"
        )

    signers = [v.signer for v in qc.votes]
    if len(set(signers)) != len(signers):
        raise CausallyImpossibleQuorum(
            f"index {qc.index}: duplicate signer in quorum {signers}"
        )

    # 1. View monotonicity across identity lifetime.
    for v in qc.votes:
        hw = peer_high_water.get(v.signer)
        if hw is not None and v.view < hw:
            raise CausallyImpossibleQuorum(
                f"index {qc.index}: signer {v.signer} attested view {v.view} "
                f"below durable high-water {hw} (rewound view state)"
            )

    # 2. The receiving agent must not be a signer below its own high-water.
    for v in qc.votes:
        if v.signer == identity.agent_id and v.view < identity.view_high_water:
            raise CausallyImpossibleQuorum(
                f"index {qc.index}: self-signature at view {v.view} below "
                f"own high-water {identity.view_high_water}"
            )

    # 3. State-provenance binding: no fork on parent digest.
    if sibling_qc is not None and sibling_qc.index == qc.index:
        parents = {v.parent_digest for v in qc.votes}
        sibling_parents = {v.parent_digest for v in sibling_qc.votes}
        if parents != sibling_parents:
            raise CausallyImpossibleQuorum(
                f"index {qc.index}: fork detected, parent digests "
                f"{parents} vs {sibling_parents}; refusing both"
            )

    # 4. Causal ordering: votes must admit a single consistent history.
    ordered = sorted(qc.votes, key=lambda v: (v.view, _digest(v)))
    for prev, cur in zip(ordered, ordered[1:]):
        if cur.view < prev.view:
            raise CausallyImpossibleQuorum(
                f"index {qc.index}: no total order over votes "
                f"({prev.signer}@{prev.view} then {cur.signer}@{cur.view})"
            )


def commit_action(
    qc: QuorumCertificate,
    identity: DurableIdentity,
    peer_high_water: dict[str, int],
    sibling_qc: QuorumCertificate | None,
    apply,
) -> None:
    assert_quorum_feasible(qc, identity, peer_high_water, sibling_qc)
    apply(qc.index, qc.votes)
