# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-speculative-branch-reconciliation-when-parallel-agent-plans-share-a-mutable-side-effect-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-speculative-branch-reconciliation-when-parallel-agent-plans-share-a-mutable-side-effect-ledger.warrant.json
# Markdown SHA-256:   b02e6b068e614dfc53e7303331d81d80241849bc538bf148cd59e2bd2d013477
# Code AST SHA-256:   ce32139ecceeb6f636bceb404eb04075d85a9f20c5342e4987070c3e5a8ee88c
# Verified Classes:   ReconciliationRefused, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable, Iterable


class ReconciliationRefused(RuntimeError):
    """Raised when a speculative merge would produce a state no branch can certify."""


@dataclass
class Branch:
    name: str
    writes: set[str]                 # ledger addresses touched
    non_commutative: bool            # contains move/increment/conditional-delete
    verifier: Callable[[set[str]], bool]


def reconcile(branches: Iterable[Branch], merged_state: set[str]) -> set[str]:
    branches = list(branches)

    # 1. Prove disjointness from journals; if not disjoint and any effect is
    #    non-commutative, the merge is inadmissible without re-validation.
    overlapping = False
    for i in range(len(branches)):
        for j in range(i + 1, len(branches)):
            if branches[i].writes & branches[j].writes:
                overlapping = True
                if branches[i].non_commutative or branches[j].non_commutative:
                    # 2. Re-validate the merged state against every branch's
                    #    invariant. Local passes are necessary, not sufficient.
                    uncertified = [
                        b.name for b in branches if not b.verifier(merged_state)
                    ]
                    if uncertified:
                        raise ReconciliationRefused(
                            f"merged ledger fails invariants of {uncertified}; "
                            "refusing speculative merge, require serialized replay"
                        )
    return merged_state


def run(branches: Iterable[Branch], merged_state: set[str]) -> set[str]:
    try:
        return reconcile(branches, merged_state)
    except ReconciliationRefused as exc:
        # Escalate: quiesce branches, replay winning strategy, re-verify.
        raise ReconciliationRefused(str(exc)) from exc
