# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-speculative-branch-was-merged-against-a-stale-sibling-snapshot-in-branch-and-merge-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-speculative-branch-was-merged-against-a-stale-sibling-snapshot-in-branch-and-merge-multi-agent-execution.warrant.json
# Markdown SHA-256:   10a54fe1f87897640e45170b6ac334b18580834efdad238cdb050b4f0d417df3
# Code AST SHA-256:   92bcbacf049e1c306d628b19771aeacbc77e8a3b274037f69fd574be1b385239
# Verified Classes:   StaleBranchSnapshotError, Delta, MergeGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class StaleBranchSnapshotError(RuntimeError):
    """Raised when a speculative delta's precondition no longer holds at merge time."""


@dataclass
class Delta:
    branch_id: str
    read_set: dict[str, Any]          # key -> value observed at fork/decision time
    write_set: dict[str, Any]          # key -> value to apply
    precondition: Callable[[dict[str, Any]], bool]  # evaluated against merge base


@dataclass
class MergeGate:
    base: dict[str, Any] = field(default_factory=dict)
    applied: list[str] = field(default_factory=list)

    def stale_read_surface(self, delta: Delta, siblings: list[Delta]) -> set[str]:
        sibling_writes: set[str] = set()
        for s in siblings:
            if s.branch_id != delta.branch_id:
                sibling_writes |= set(s.write_set)
        return set(delta.read_set) & sibling_writes

    def apply(self, delta: Delta, siblings: list[Delta]) -> None:
        surface = self.stale_read_surface(delta, siblings)
        for key in surface:
            observed = delta.read_set[key]
            current = self.base.get(key)
            if observed != current:
                # The branch's precondition was evaluated against a world that
                # a sibling has since replaced. Re-run, do not conflict-resolve.
                raise StaleBranchSnapshotError(
                    f"branch {delta.branch_id} assumed {key}={observed!r} "
                    f"but merge base has {key}={current!r}; delta is obsolete"
                )
        if not delta.precondition(self.base):
            raise StaleBranchSnapshotError(
                f"branch {delta.branch_id} precondition false at apply time"
            )
        self.base.update(delta.write_set)
        self.applied.append(delta.branch_id)


def reconcile(gate: MergeGate, deltas: list[Delta]) -> list[str]:
    rerun: list[str] = []
    for d in deltas:
        try:
            gate.apply(d, deltas)
        except StaleBranchSnapshotError:
            rerun.append(d.branch_id)
    return rerun
