# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-merge-speculative-agent-branches-whose-partial-results-fail-byzantine-quorum-intersection.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-merge-speculative-agent-branches-whose-partial-results-fail-byzantine-quorum-intersection.warrant.json
# Markdown SHA-256:   80a4b93997f03ea7e79adb21a821c0521991981c79f3af7438b51ebb8d3c0dd1
# Code AST SHA-256:   ec9c53d2a77ed5491d91aee1fe51a6adcbf80f89cae4899e305822f563228a9f
# Verified Classes:   MergePoisonedError, MergeQuorumError, Partial, MergeResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class MergePoisonedError(RuntimeError):
    """Raised when a speculative merge would commit a field whose provenance
    is not a subset of the honest-attested consumed partials."""
    pass


class MergeQuorumError(RuntimeError):
    """Raised when the merge closure lacks n - f honest-attested partials."""
    pass


@dataclass(frozen=True)
class Partial:
    partial_id: str
    branch_id: str
    attested: bool          # per-partial attestation, not per-branch
    fields: frozenset       # field names this partial contributes
    is_prefix_anchor: bool = False


@dataclass
class MergeResult:
    committed_fields: dict          # field -> value
    provenance: dict = field(default_factory=dict)  # field -> set(partial_id)
    consumed: set = field(default_factory=set)


def assert_merge_safe(
    partials: Iterable[Partial],
    merged: MergeResult,
    n: int,
    f: int,
) -> None:
    partials = list(partials)
    honest_ids = {p.partial_id for p in partials if p.attested}

    # 1. Merge-closure quorum: consumed partials must include n - f honest ones.
    consumed_honest = merged.consumed & honest_ids
    if len(consumed_honest) < (n - f):
        raise MergeQuorumError(
            f"merge closure has {len(consumed_honest)} honest partials, "
            f"need {n - f} of {n}"
        )

    # 4. Prefix-anchor exclusion: no unattested partial may anchor a prefix.
    for p in partials:
        if p.is_prefix_anchor and not p.attested:
            raise MergePoisonedError(
                f"unattested partial {p.partial_id} used as prefix anchor"
            )

    # 2. Every committed field's provenance must be honest-only.
    for fld, prov in merged.provenance.items():
        if not prov <= honest_ids:
            raise MergePoisonedError(
                f"field {fld!r} depends on unattested partials "
                f"{sorted(prov - honest_ids)}"
            )


def commit_merge(partials, merged, n, f):
    assert_merge_safe(partials, merged, n, f)
    return merged.committed_fields
