# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-merge-unsafe-sibling-branch-before-committing-a-speculative-plan-tree.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-merge-unsafe-sibling-branch-before-committing-a-speculative-plan-tree.warrant.json
# Markdown SHA-256:   7fe61b445a88f60b5f1451e76a7b731fcf8685076df112242a1dc34d2dd909ca
# Code AST SHA-256:   320d6f6cd87d06662aeed616016ba52848becff7e4e0e6936a3544eae6dbbea9
# Verified Classes:   UnmergeableBranchError, Effect, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class UnmergeableBranchError(RuntimeError):
    """Raised when a branch reports success but cannot legally merge into the committed lineage."""


@dataclass
class Effect:
    resource: str
    kind: str            # "patch" or "replace"
    fields: set[str]
    read_rev: int


@dataclass
class Branch:
    name: str
    status: str                      # "success" | "failure"
    declared_write_set: set[str]
    effects: list[Effect] = field(default_factory=list)


def classify_branch(branch: Branch, current_rev: int, committed_fields: dict[str, set[str]]) -> str:
    if branch.status != "success":
        return "ROLLBACK"

    for eff in branch.effects:
        # Containment check runs at call time in a correct runtime; re-asserted here.
        if eff.resource not in branch.declared_write_set:
            raise UnmergeableBranchError(
                f"branch {branch.name!r} mutated undeclared resource {eff.resource!r}"
            )
        if eff.kind == "replace":
            # Whole-object replacement from a stale read silently clobbers siblings.
            if eff.read_rev != current_rev:
                raise UnmergeableBranchError(
                    f"branch {branch.name!r} whole-object replace on {eff.resource!r} "
                    f"from read_rev={eff.read_rev} against head {current_rev}"
                )
        if eff.kind == "patch" and eff.read_rev != current_rev:
            # Stale read is only legal if the patch is field-disjoint from what landed since.
            landed = committed_fields.get(eff.resource, set())
            if eff.fields & landed:
                raise UnmergeableBranchError(
                    f"branch {branch.name!r} patch on {eff.resource!r} overlaps "
                    f"committed fields {eff.fields & landed}"
                )
            return "REBASE"

    return "COMMIT"


def merge_gate(branches: list[Branch], current_rev: int, committed_fields: dict[str, set[str]]) -> list[tuple[str, str]]:
    decisions = []
    for b in branches:
        try:
            decisions.append((b.name, classify_branch(b, current_rev, committed_fields)))
        except UnmergeableBranchError:
            # Success-but-unmergeable must be forced to rollback, never committed.
            decisions.append((b.name, "ROLLBACK"))
    return decisions
