# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-quorum-signed-task-commitment-as-non-transferable-across-byzantine-agent-subgroups-during-shared-state-reconc.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-quorum-signed-task-commitment-as-non-transferable-across-byzantine-agent-subgroups-during-shared-state-reconc.warrant.json
# Markdown SHA-256:   f7473d5ed1337674da1550d8cfcbde88d69969ffaf8e08a8be9b35b31e987c81
# Code AST SHA-256:   de06bc148a2542e0a1b650a069023e758b9ae183e013e1b4d072e0f8aceae69d
# Verified Classes:   QuorumReconciliationError, Certificate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Optional


class QuorumReconciliationError(RuntimeError):
    """Raised when two quorum certificates cannot be safely composed."""


@dataclass(frozen=True)
class Certificate:
    slot: str
    proposal: str
    epoch: int
    signers: FrozenSet[str]
    reconfig_proof: Optional[str]  # proof chaining this epoch to a prior one


def reconcile(
    cert_a: Certificate,
    cert_b: Certificate,
    f: int,
    byzantine: FrozenSet[str],
) -> Certificate:
    """Return the single committed certificate, or raise.

    Invariant: two certificates for the same slot are only composable if
    (a) same epoch and signer intersection >= f+1, or
    (b) higher epoch carries a valid reconfiguration proof.
    """
    if cert_a.slot != cert_b.slot:
        raise QuorumReconciliationError(
            f"slot mismatch: {cert_a.slot} vs {cert_b.slot}"
        )

    if cert_a.epoch == cert_b.epoch:
        intersection = cert_a.signers & cert_b.signers
        honest_overlap = intersection - byzantine
        if len(intersection) < f + 1 or len(honest_overlap) < f + 1:
            raise QuorumReconciliationError(
                f"slot {cert_a.slot} epoch {cert_a.epoch}: quorum intersection "
                f"{len(intersection)} (honest {len(honest_overlap)}) < f+1={f+1}; "
                f"certificates are non-composable — escalate to membership audit"
            )
        # Same epoch, sufficient honest overlap: deterministic causal tiebreak.
        return max((cert_a, cert_b), key=lambda c: (c.epoch, c.proposal))

    # Epoch divergence: only a proven reconfiguration may supersede.
    higher, lower = (
        (cert_a, cert_b) if cert_a.epoch > cert_b.epoch else (cert_b, cert_a)
    )
    if higher.reconfig_proof is None:
        raise QuorumReconciliationError(
            f"slot {higher.slot}: epoch {higher.epoch} supersedes {lower.epoch} "
            f"without reconfiguration proof — cannot validate membership view; "
            f"mark slot CONTESTED"
        )
    return higher
