# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-commits-when-parallel-rollback-invalidates-a-sibling-s-already-merged-write.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-commits-when-parallel-rollback-invalidates-a-sibling-s-already-merged-write.warrant.json
# Markdown SHA-256:   5f1222dc23b185be6f8edfcdee2ec7c8d2bf0e24a78a632d892f89796e64dec3
# Code AST SHA-256:   27200b1965d59a1441bde7fbc87dc34514430767349791438ce4b4dbd3682777
# Verified Classes:   LineageUnresolvedError, Write
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class LineageUnresolvedError(RuntimeError):
    """Raised when rollback would revert a resource whose dependency
    relationship to a surviving branch is unknown. Fail closed."""
    pass


@dataclass
class Write:
    path: str
    branch_id: str
    read_set: Set[str] = field(default_factory=set)


def compute_closure(winner_id: str, writes: list[Write]) -> Set[str]:
    """Resources the winner transitively depends on, via read-sets of
    its writes. Returns the set of paths that must NOT be reverted."""
    closure: Set[str] = set()
    frontier = [w for w in writes if w.branch_id == winner_id]
    seen: Set[str] = set()
    while frontier:
        w = frontier.pop()
        if w.path in seen:
            continue
        seen.add(w.path)
        closure |= w.read_set
        # any write to a resource in the closure becomes part of it
        for other in writes:
            if other.path in w.read_set and other.branch_id != winner_id:
                frontier.append(other)
    return closure


def rollback(winner_id: str, writes: list[Write], known_paths: Set[str]) -> Set[str]:
    """Revert non-winner writes, promoting those in the winner's closure.
    Raises LineageUnresolvedError if a non-winner write touches a path
    in the winner's closure but that path's provenance is unknown."""
    closure = compute_closure(winner_id, writes)
    promoted: Set[str] = set()
    reverted: Set[str] = set()
    for w in writes:
        if w.branch_id == winner_id:
            continue
        if w.path in closure:
            if w.path not in known_paths:
                raise LineageUnresolvedError(
                    f"cannot safely revert {w.path!r} from branch "
                    f"{w.branch_id!r}: it is in winner {winner_id!r}'s "
                    f"closure but provenance is unresolved"
                )
            promoted.add(w.path)  # re-tag to winner, do not revert
        else:
            reverted.add(w.path)
    return promoted | reverted


def merge_gate(winner_id: str, writes: list[Write], known_paths: Set[str]) -> None:
    try:
        rollback(winner_id, writes, known_paths)
    except LineageUnresolvedError as exc:
        # surface to orchestrator; do not silently proceed
        raise LineageUnresolvedError(
            f"merge aborted for winner {winner_id!r}: {exc}"
        ) from exc
