# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-merge-a-speculative-branch-when-byzantine-peers-report-divergent-pre-images.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-merge-a-speculative-branch-when-byzantine-peers-report-divergent-pre-images.warrant.json
# Markdown SHA-256:   0f5ff5a1bb688823af9eb429abf377052d2d2c4470d9311fb425afb6a2e4d612
# Code AST SHA-256:   d6eeecd07673058cc66da7dc5ce9ae0a5cff9911bf1669430bb1c386484ddf0f
# Verified Classes:   SpeculativeMergeRefused, ForkToken, BranchResult, Checkpoint
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class SpeculativeMergeRefused(RuntimeError):
    """Raised when a speculative branch merge fails any admission invariant."""
    pass


@dataclass
class ForkToken:
    branch_id: str
    checkpoint_digest: str
    dispatch_nonce: str
    signature: str  # coordinator-signed over (branch_id, checkpoint_digest, dispatch_nonce)


@dataclass
class BranchResult:
    token: ForkToken
    reported_pre_image: str
    delta: dict
    delta_digest: str


@dataclass
class Checkpoint:
    digest: str
    version: int
    ownership: dict  # field_name -> set(branch_ids) authorized to write
    body: dict = field(default_factory=dict)


def verify_token(token: ForkToken, coordinator_pubkey: str) -> bool:
    # Placeholder for real signature verification; must bind all three fields.
    expected = hashlib.sha256(
        f"{token.branch_id}|{token.checkpoint_digest}|{token.dispatch_nonce}".encode()
    ).hexdigest()
    return token.signature == expected


def admit_branch_merge(
    branch: BranchResult,
    checkpoint: Checkpoint,
    quorum_attestations: dict,  # reported_pre_image -> count of independent branches
    byzantine_bound_f: int,
    coordinator_pubkey: str,
) -> str:
    # V1: fork-identity binding
    if not verify_token(branch.token, coordinator_pubkey):
        raise SpeculativeMergeRefused(
            f"branch {branch.token.branch_id}: fork token signature invalid"
        )
    if branch.token.checkpoint_digest != branch.reported_pre_image:
        raise SpeculativeMergeRefused(
            f"branch {branch.token.branch_id}: reported pre-image "
            f"{branch.reported_pre_image} contradicts its own fork token "
            f"{branch.token.checkpoint_digest}; refusing rebase, re-dispatch required"
        )

    # V2: pre-image quorum against coordinator record
    if branch.reported_pre_image != checkpoint.digest:
        raise SpeculativeMergeRefused(
            f"branch {branch.token.branch_id}: pre-image {branch.reported_pre_image} "
            f"!= coordinator checkpoint {checkpoint.digest}; coordinator record suspect"
        )
    if quorum_attestations.get(branch.reported_pre_image, 0) < (byzantine_bound_f + 1):
        raise SpeculativeMergeRefused(
            f"branch {branch.token.branch_id}: pre-image lacks f+1 attestation "
            f"({quorum_attestations.get(branch.reported_pre_image, 0)} < {byzantine_bound_f + 1})"
        )

    # V3: delta authorization against pre-image ownership map
    for field_name in branch.delta:
        owners = checkpoint.ownership.get(field_name, set())
        if branch.token.branch_id not in owners:
            raise SpeculativeMergeRefused(
                f"branch {branch.token.branch_id}: delta writes field '{field_name}' "
                f"with no ownership grant in pre-image {checkpoint.digest}"
            )

    # V4: monotonic version advance derived from pre-image + delta digests
    new_version = hashlib.sha256(
        f"{checkpoint.digest}|{branch.delta_digest}".encode()
    ).hexdigest()
    if new_version == checkpoint.digest:
        raise SpeculativeMergeRefused(
            f"branch {branch.token.branch_id}: version advance collided with pre-image"
        )
    return new_version
