# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-speculative-branch-merge-as-a-write-conflict-rather-than-a-benign-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-speculative-branch-merge-as-a-write-conflict-rather-than-a-benign-reconciliation.warrant.json
# Markdown SHA-256:   61f6686ee6dd919e1576215da2d35e62d20022976b3fb38727902cd963795eff
# Code AST SHA-256:   d2170910e60befe4bff8a65f067c66df036a0560dd3c2c55dc9202e2ffb1fab9
# Verified Classes:   SpeculativeMergeConflict, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class SpeculativeMergeConflict(RuntimeError):
    """Raised when a branch merge would silently drop a stale-read-derived write."""


@dataclass
class Branch:
    branch_id: str
    # location -> epoch at which the branch read it
    read_witness: dict[str, int] = field(default_factory=dict)
    # location -> epoch at which the branch wrote it
    write_set: dict[str, int] = field(default_factory=dict)


def merge_branches(branches: list[Branch]) -> dict[str, int]:
    merged: dict[str, int] = {}
    for b in branches:
        for loc, write_epoch in b.write_set.items():
            for other in branches:
                if other is b:
                    continue
                if loc not in other.read_witness:
                    continue
                # other read this location; did it read before we wrote?
                if other.read_witness[loc] < write_epoch:
                    # other's downstream writes may be derived from a stale read
                    raise SpeculativeMergeConflict(
                        f"branch {other.branch_id} read {loc!r} at epoch "
                        f"{other.read_witness[loc]} but branch {b.branch_id} "
                        f"wrote it at epoch {write_epoch}; merge would lose "
                        f"an update derived from a stale read"
                    )
            merged[loc] = write_epoch
    return merged
