# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-quorum-split-speculation-collapse-in-federated-speculative-execution-with-cross-org-quorum-validation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-quorum-split-speculation-collapse-in-federated-speculative-execution-with-cross-org-quorum-validation.warrant.json
# Markdown SHA-256:   074b13bc13565b22b2ba8017d86c0ff7416d2005736a39f24db9f7bf9aa07ed4
# Code AST SHA-256:   5bf62b6fd058dbadfb72cc5c6cf4edc0973781ddee5a079a5c1220516f40f74b
# Verified Classes:   SplitSpeculationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SplitSpeculationError(RuntimeError):
    """Raised when two committed speculative branches violate the global intersection floor."""
    pass


def validate_cross_org_branch(branch, global_epoch, f):
    """
    branch: dict with keys 'validators' (set), 'epoch' (int), 'branch_id' (str)
    global_epoch: the maximum epoch this instance has observed
    f: fault tolerance parameter; honest intersection floor is f + 1
    """
    validators = set(branch["validators"])
    if len(validators) < 2 * f + 1:
        raise SplitSpeculationError(
            f"branch {branch['branch_id']} has {len(validators)} validators, "
            f"below quorum floor {2 * f + 1}"
        )
    if branch["epoch"] != global_epoch:
        # A vote issued under a stale epoch can form a second speculative universe.
        raise SplitSpeculationError(
            f"branch {branch['branch_id']} epoch {branch['epoch']} != "
            f"global epoch {global_epoch}; refusing to treat as globally valid"
        )
    return True


def check_branch_intersection(branch_a, branch_b, f):
    """
    Enforce the global intersection invariant across two committed branches.
    This is the check that catches quorum-split speculation collapse.
    """
    overlap = set(branch_a["validators"]) & set(branch_b["validators"])
    if len(overlap) < f + 1:
        raise SplitSpeculationError(
            f"committed branches {branch_a['branch_id']} and {branch_b['branch_id']} "
            f"intersect in {len(overlap)} validators, below honest floor {f + 1}; "
            f"federation is in split-speculation state"
        )
    return True
