# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-replay-identical-speculative-branch-as-non-authoritative-when-peer-agents-hold-divergent-partial-observ.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-replay-identical-speculative-branch-as-non-authoritative-when-peer-agents-hold-divergent-partial-observ.warrant.json
# Markdown SHA-256:   64a890c561c5ed496746f274c3b14b3554d8bc6ab6252f4e13ac0bad19e898f4
# Code AST SHA-256:   d955a2a5e2a5275f56a0ed8170d3a0abfbb087b1a0fc66f7a4b2cd7ab96450e1
# Verified Classes:   MaskAuthorityError, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class MaskAuthorityError(RuntimeError):
    """Raised when a replay-identical branch lacks observation-mask authority."""
    pass


@dataclass(frozen=True)
class Branch:
    branch_id: str
    parent_hash: str
    state_hash: str
    author_mask: frozenset          # fields the author could observe
    touched_fields: frozenset       # fields the event log read or wrote
    event_log: tuple = field(default=())


def replay_identical(branch: Branch, executor) -> bool:
    """Deterministic executor reproduces the published hash."""
    return executor(branch.event_log) == branch.state_hash


def reconcile(coordinator_mask: frozenset,
              branches: list,
              executor) -> Branch:
    """
    Select an authoritative branch. Replay identity is necessary but
    NOT sufficient: the author's mask must cover every touched field,
    and the coordinator must be able to verify those fields itself.
    """
    candidates = []
    for b in branches:
        if not replay_identical(b, executor):
            continue  # genuine replay failure; skip

        # Replay-identical, but is it observation-valid?
        author_blind = not b.touched_fields.issubset(b.author_mask)
        coord_blind = not b.touched_fields.issubset(coordinator_mask)

        if author_blind or coord_blind:
            # A write to a field outside the author's mask means the
            # hash was computed over a projection that excluded the
            # disputed field. Determinism here is vacuous.
            raise MaskAuthorityError(
                f"branch {b.branch_id} replay-identical but mask-blind: "
                f"touched={sorted(b.touched_fields)} "
                f"author_mask={sorted(b.author_mask)} "
                f"coord_mask={sorted(coordinator_mask)}"
            )
        candidates.append(b)

    if not candidates:
        raise MaskAuthorityError("no observation-valid branch to reconcile")

    # Only now is longest-log-wins a defensible tiebreak, because every
    # surviving branch was verified under a superset mask.
    return max(candidates, key=lambda b: len(b.event_log))
