# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-speculative-branch-as-quorum-attested-when-the-attestation-set-is-internally-consistent-but-causally-disjoint-from-the-b.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-speculative-branch-as-quorum-attested-when-the-attestation-set-is-internally-consistent-but-causally-disjoint-from-the-b.warrant.json
# Markdown SHA-256:   44f4f8e8e5719d007e150fe9812edf1c1ac8e07c7847c836f0ec4ff381d55e89
# Code AST SHA-256:   63560e697bba0e5375d0d1441e13bdc0b3af8801f00e7962a1bd23893e729ac2
# Verified Classes:   CausalDisjointQuorumError, Attestation, SpeculativeBranch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class CausalDisjointQuorumError(RuntimeError):
    """Raised when a content quorum is met but attestations are not
    causally closed under the speculative branch's declared origin."""


@dataclass(frozen=True)
class Attestation:
    peer_id: str
    branch_id: str
    predicate_ok: bool
    parent_checkpoint: str
    episodic_version: str
    signature: str  # assumed already verified upstream


@dataclass(frozen=True)
class SpeculativeBranch:
    branch_id: str
    parent_checkpoint: str
    episodic_version: str


def verify_quorum_before_merge(
    branch: SpeculativeBranch,
    attestations: Sequence[Attestation],
    current_checkpoint: str,
    current_episodic_version: str,
    n: int,
    f: int,
) -> None:
    threshold = -(-(2 * f + 1) // n)  # ceil((2f+1)/n)

    content_ok = [
        a for a in attestations
        if a.branch_id == branch.branch_id and a.predicate_ok
    ]
    if len(content_ok) < threshold:
        raise CausalDisjointQuorumError(
            f"content quorum unmet for {branch.branch_id}: "
            f"{len(content_ok)}/{threshold}"
        )

    # Lineage closure is the gate, not a tiebreaker.
    lineage_ok = [
        a for a in content_ok
        if a.parent_checkpoint == branch.parent_checkpoint
        and a.episodic_version == branch.episodic_version
    ]
    if len(lineage_ok) < threshold:
        skew = {
            (a.parent_checkpoint, a.episodic_version) for a in content_ok
        }
        raise CausalDisjointQuorumError(
            f"causally disjoint quorum for {branch.branch_id}: "
            f"content={len(content_ok)} lineage={len(lineage_ok)} "
            f"required={threshold} observed_origins={skew}"
        )

    # The branch's origin must be the world-state the merger will resume from,
    # or an explicitly declared ancestor with a reconciliation step.
    if (
        branch.parent_checkpoint != current_checkpoint
        or branch.episodic_version != current_episodic_version
    ):
        raise CausalDisjointQuorumError(
            f"branch {branch.branch_id} origin "
            f"({branch.parent_checkpoint},{branch.episodic_version}) "
            f"!= merge checkpoint "
            f"({current_checkpoint},{current_episodic_version}); "
            f"re-derive, do not re-label"
        )
