# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-admit-a-semantically-clean-branch-merge-that-silently-discards-a-byzantine-peer-s-poisoned-state.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-admit-a-semantically-clean-branch-merge-that-silently-discards-a-byzantine-peer-s-poisoned-state.warrant.json
# Markdown SHA-256:   44038a465e3e1aba85cb1fb4bf68900c00c91ff8fa96bd4949368f5505ea7c09
# Code AST SHA-256:   d6295d798b7018480265026d4f074981a3fffb44196187c0364bcbc41e488e9d
# Verified Classes:   UncorroboratedNovelAssertion, Assertion, BranchDelta
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class UncorroboratedNovelAssertion(RuntimeError):
    """Raised when a merge would commit a novel key without quorum corroboration
    or commit-time entailment re-derivation against its cited source."""


@dataclass
class Assertion:
    key: str
    value: object
    citation: str
    confidence: float
    branch_id: str


@dataclass
class BranchDelta:
    branch_id: str
    attested: bool
    assertions: List[Assertion] = field(default_factory=list)


def merge_speculative_branches(
    deltas: List[BranchDelta],
    quorum: int,
    entail: Callable[[str, str, object], bool],
    shared_keys: Set[str],
) -> Dict[str, object]:
    """
    Merge branch deltas under Byzantine assumptions.

    - shared_keys: keys the schema already permits (closed-world core).
    - Novel keys (not in shared_keys) require >= quorum independent *attested*
      branches asserting the same (key, value), OR commit-time entailment
      against the cited source. Confidence is never used to win a novel key.
    - Any winning assertion failing entailment aborts the merge.
    """
    # Bucket assertions by (key, value) to find corroboration, not by confidence.
    buckets: Dict[Tuple[str, object], List[Assertion]] = {}
    for d in deltas:
        for a in d.assertions:
            if not d.attested:
                # Unattested branches may corroborate nothing.
                continue
            buckets.setdefault((a.key, a.value), []).append(a)

    merged: Dict[str, object] = {}
    for (key, value), supporters in buckets.items():
        independent = {a.branch_id for a in supporters}
        if key in shared_keys:
            # Closed-world core: quorum over independent attested branches.
            if len(independent) < quorum:
                continue
        else:
            # Novel key: corroboration OR entailment. Confidence is irrelevant.
            corroborated = len(independent) >= quorum
            if not corroborated:
                citation = supporters[0].citation
                if not entail(citation, key, value):
                    raise UncorroboratedNovelAssertion(
                        f"novel key {key!r}={value!r} from branch "
                        f"{supporters[0].branch_id!r} has no quorum "
                        f"({len(independent)}/{quorum}) and its citation "
                        f"{citation!r} does not entail the assertion; "
                        f"refusing to commit an unopposed lie"
                    )
        # Commit-time entailment re-check applies to every winner.
        for a in supporters:
            if not entail(a.citation, key, value):
                raise UncorroboratedNovelAssertion(
                    f"assertion {key!r}={value!r} from {a.branch_id!r} "
                    f"fails entailment against {a.citation!r} at commit"
                )
        merged[key] = value

    return merged
