# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-merge-integrity-has-collapsed-under-byzantine-quorum-participants.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-merge-integrity-has-collapsed-under-byzantine-quorum-participants.warrant.json
# Markdown SHA-256:   dcd542c14a99b745b67de1fe76d2d97d81eeb35db486e4210fee447ca4f0e684
# Code AST SHA-256:   6240e0920d5fafbef4f8587f28eeeaa958f2723311c6e3df633bd5f6d855fc66
# Verified Classes:   MergeIntegrityError, BranchDiff, MergeResult
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, List


class MergeIntegrityError(RuntimeError):
    """Raised when a speculative branch merge violates the authorship-quorum binding."""
    pass


@dataclass
class BranchDiff:
    branch_id: str
    writes: Dict[str, str]          # node_id -> value
    self_confidence: float          # UNTRUSTED: Byzantine-controllable
    voted_nodes: Set[str] = field(default_factory=set)


@dataclass
class MergeResult:
    merged: Dict[str, str]
    provenance: Dict[str, str]      # node_id -> authoring branch_id


def merge_speculative_branches(
    branches: List[BranchDiff],
    adjudication_node: str,
    quorum_threshold: int,
) -> MergeResult:
    """
    Merge speculative branches with per-node provenance and Byzantine checks.

    Invariants enforced:
      1. Authorship-quorum binding: every surviving node's author voted on it.
      2. Adjudication anchor: every branch must touch the adjudication node,
         forcing conflict-graph connectivity.
      3. Quorum-collapse boundary: reject if honest count after quarantine < threshold.
    """
    if not branches:
        raise MergeIntegrityError("no branches to merge")

    # --- Check 2: adjudication anchor (conflict-graph connectivity) ---
    for b in branches:
        if adjudication_node not in b.writes:
            raise MergeIntegrityError(
                f"branch {b.branch_id} did not write adjudication node "
                f"{adjudication_node!r}; conflict graph may be disconnected"
            )

    # --- Build per-node author sets (coordinator-observed, not self-reported) ---
    node_authors: Dict[str, Set[str]] = {}
    for b in branches:
        for node in b.writes:
            node_authors.setdefault(node, set()).add(b.branch_id)

    # --- Detect conflict-degree-zero anomaly on contested nodes ---
    # A branch that writes only uncontested nodes while the adjudication node
    # is contested is the signature of adversarial avoidance.
    adjudication_writers = node_authors.get(adjudication_node, set())
    if len(adjudication_writers) < 2:
        raise MergeIntegrityError(
            f"adjudication node {adjudication_node!r} has only "
            f"{len(adjudication_writers)} writer(s); cannot adjudicate"
        )

    # --- Merge with per-node provenance; tiebreak by arrival order, NOT confidence ---
    merged: Dict[str, str] = {}
    provenance: Dict[str, str] = {}
    for b in branches:  # branches assumed pre-sorted by coordinator-observed arrival
        for node, value in b.writes.items():
            # Authorship-quorum binding check happens post-merge below;
            # here we record the last coordinator-observed writer.
            merged[node] = value
            provenance[node] = b.branch_id

    # --- Check 1: authorship-quorum binding per node ---
    for node, author in provenance.items():
        author_branch = next(b for b in branches if b.branch_id == author)
        if node not in author_branch.voted_nodes:
            raise MergeIntegrityError(
                f"authorship-quorum binding violated at node {node!r}: "
                f"author {author!r} did not vote on the node it wrote"
            )

    # --- Check 3: quorum-collapse boundary ---
    # If any single branch's removal drops the writer count below threshold,
    # we cannot distinguish f Byzantine faults from a Byzantine majority.
    for node, writers in node_authors.items():
        if len(writers) - 1 < quorum_threshold:
            raise MergeIntegrityError(
                f"quorum-collapse boundary at node {node!r}: "
                f"{len(writers)} writers, threshold {quorum_threshold}; "
                f"removing one suspect leaves insufficient quorum"
            )

    return MergeResult(merged=merged, provenance=provenance)
