# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-merge-speculative-agent-branches-whose-writes-were-validated-against-a-shared-memory-store-snapshot-that.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-merge-speculative-agent-branches-whose-writes-were-validated-against-a-shared-memory-store-snapshot-that.warrant.json
# Markdown SHA-256:   bf7ae0df34869ffe894dfcba0fe2a6e8568a6d807519d22b1e7ae26abba9a1a3
# Code AST SHA-256:   177d9f7f24803e6cf074e497a32672ba7064cc709d3ff13551d6b477a61dce8f
# Verified Classes:   StaleBranchMergeError, ValidationToken, BranchWrite
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class StaleBranchMergeError(RuntimeError):
    """Raised when a speculative branch's validation token is expired at merge time."""
    pass


@dataclass(frozen=True)
class ValidationToken:
    snapshot_version: int
    asserted: Mapping[str, Callable[[Mapping[str, Any]], bool]]


@dataclass(frozen=True)
class BranchWrite:
    key: str
    value: Any
    token: ValidationToken


def merge_branch(
    write: BranchWrite,
    current_head: Mapping[str, Any],
    head_version: int,
    store_invariants: Mapping[str, Callable[[Mapping[str, Any]], bool]],
) -> Mapping[str, Any]:
    token = write.token

    # Fast path: head unchanged since the branch read -> token still authoritative.
    if head_version == token.snapshot_version:
        projected = {**current_head, write.key: write.value}
    else:
        # Head advanced: every asserted predicate must re-validate against the head.
        failed = [name for name, pred in token.asserted.items() if not pred(current_head)]
        if failed:
            raise StaleBranchMergeError(
                f"Branch write to {write.key!r} read snapshot v{token.snapshot_version} "
                f"but head is v{head_version}; predicates {failed} no longer hold. "
                f"Re-run the branch against the current head; do not patch the write."
            )
        projected = {**current_head, write.key: write.value}

    # Even with predicates satisfied, the merged projection must satisfy store invariants.
    for inv_name, inv in store_invariants.items():
        if not inv(projected):
            raise StaleBranchMergeError(
                f"Merging {write.key!r} violates store invariant {inv_name!r} "
                f"against head v{head_version}. Lost-update/write-skew rejected."
            )

    return projected
