# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-merged-plan-whose-individual-branches-each-carry-a-valid-byzantine-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-merged-plan-whose-individual-branches-each-carry-a-valid-byzantine-quorum.warrant.json
# Markdown SHA-256:   71b394a4a16e19c8678a07c6db52180e6af7550d15e63633fc9d9551ce0b51d8
# Code AST SHA-256:   8384948fa08a35ff3c53fbedb7741a323c5992173e53cbc2c0ac784f058e3da6
# Verified Classes:   CrossBranchQuorumViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CrossBranchQuorumViolation(RuntimeError):
    """Raised when a merged plan's cross-branch predicates lack a union-cohort quorum."""
    pass


def admit_merge(branches, cross_predicates, union_cohort, threshold):
    """
    branches: list of {snapshot, signers:set, predicates:set}
    cross_predicates: set of predicates shared across branches
    union_cohort: set of all eligible signers across cohorts
    threshold: required fraction of union_cohort (e.g. 0.67)
    """
    # 1. Build union snapshot; incomparable snapshots are a hard reject.
    union_snapshot = {}
    for b in branches:
        for k, v in b["snapshot"].items():
            if k in union_snapshot and union_snapshot[k] != v:
                raise CrossBranchQuorumViolation(
                    f"incomparable snapshots on {k}: {union_snapshot[k]} vs {v}"
                )
            union_snapshot[k] = v

    # 2. For each cross-branch predicate, count union-cohort signers that
    #    explicitly attested it (local attestation does not compose).
    required = max(1, int(len(union_cohort) * threshold))
    for pred in cross_predicates:
        attesting = set()
        for b in branches:
            if pred in b["predicates"]:
                # only signers whose snapshot is a subset of union_snapshot
                if all(union_snapshot.get(k) == v for k, v in b["snapshot"].items()):
                    attesting |= (b["signers"] & union_cohort)
        if len(attesting) < required:
            raise CrossBranchQuorumViolation(
                f"predicate {pred} attested by {len(attesting)}/{required} "
                f"union-cohort signers; local quorums do not compose"
            )
    return True
