# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-byzantine-quorum-that-is-arithmetically-valid-but-temporally-impossible.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-byzantine-quorum-that-is-arithmetically-valid-but-temporally-impossible.warrant.json
# Markdown SHA-256:   eaa35119b0e7a57193d478b95bab1b60fb56fa69e30f04d1d4d86a38b1362261
# Code AST SHA-256:   7bdbd221192ab854a23b7e318597a2ece4c0e996460d66166bab5cdbeb484cd9
# Verified Classes:   CausalQuorumError, Attestation, OrchestratorView
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Dict, List, Optional, Set


class CausalQuorumError(RuntimeError):
    """Raised when a quorum certificate is cardinality-valid but causally impossible."""
    pass


@dataclass(frozen=True)
class Attestation:
    signer: str
    seq: int
    prev: str          # digest of prior attestation in this signer's chain
    request_digest: str
    signature_valid: bool


@dataclass
class OrchestratorView:
    last_committed_seq: Dict[str, int]
    last_committed_digest: str
    freshness_window: int


def validate_quorum(
    cert: List[Attestation],
    view: OrchestratorView,
    f: int,
) -> None:
    """
    Enforce cardinality AND causality AND freshness.
    Raises CausalQuorumError on the first invariant violation.
    """
    # (1) Cardinality over distinct signers.
    signers: Set[str] = set()
    for a in cert:
        if not a.signature_valid:
            raise CausalQuorumError(f"invalid signature from {a.signer}")
        if a.signer in signers:
            # Same signer twice in one batch = equivocation evidence, not a
            # duplicate to be deduplicated. Reject the whole batch.
            raise CausalQuorumError(
                f"equivocation: {a.signer} appears twice in certificate batch"
            )
        signers.add(a.signer)
    if len(signers) < 2 * f + 1:
        raise CausalQuorumError(
            f"cardinality {len(signers)} < 2f+1 = {2 * f + 1}"
        )

    # (2) Freshness: no rolled-back seq beyond the reordering window.
    for a in cert:
        floor = view.last_committed_seq.get(a.signer, 0)
        if a.seq < floor - view.freshness_window:
            raise CausalQuorumError(
                f"stale seq from {a.signer}: {a.seq} < {floor} - W={view.freshness_window}"
            )

    # (3) Causality: prev-chain must form a single tree rooted at the
    # orchestrator's last committed digest. Any second root among
    # attestations above the freshness floor is a fork.
    roots: Set[str] = set()
    for a in cert:
        floor = view.last_committed_seq.get(a.signer, 0)
        if a.seq > floor and a.prev != view.last_committed_digest:
            # This attestation chains from something other than our
            # committed head. It is a fork root unless it descends from
            # another attestation in this batch.
            if not any(
                b.signer != a.signer and b.seq < a.seq and b.prev == a.prev
                for b in cert
            ):
                roots.add(a.prev)
    if len(roots) > 1:
        raise CausalQuorumError(
            f"causal fork: {len(roots)} disjoint prev-roots in certificate"
        )

    # (4) Ancestry: every attestation with seq > floor must chain to a
    # prev that is either the committed head or a prev emitted by another
    # attestation in this batch with strictly smaller seq.
    by_prev: Dict[str, List[Attestation]] = {}
    for a in cert:
        by_prev.setdefault(a.prev, []).append(a)
    for a in cert:
        floor = view.last_committed_seq.get(a.signer, 0)
        if a.seq <= floor:
            continue
        if a.prev == view.last_committed_digest:
            continue
        ancestors = by_prev.get(a.prev, [])
        if not any(b.seq < a.seq for b in ancestors):
            raise CausalQuorumError(
                f"orphan attestation from {a.signer} at seq {a.seq}: "
                f"prev {a.prev[:12]} has no smaller-seq ancestor in batch"
            )


def commit_side_effect(
    cert: List[Attestation],
    view: OrchestratorView,
    f: int,
    payload: bytes,
) -> str:
    validate_quorum(cert, view, f)
    # Only reached if cardinality, freshness, and causality all hold.
    return hashlib.sha256(payload).hexdigest()
