# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-merge-a-speculative-branch-sibling-divergence-after-a-shared-prefix-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-merge-a-speculative-branch-sibling-divergence-after-a-shared-prefix-checkpoint.warrant.json
# Markdown SHA-256:   76a0cbf9449931fef98301b98ad5d6c24331716b5cdf7ef8f9d10ee43e0c6eee
# Code AST SHA-256:   5dec44a67af0560f29c9926762b2db74fff984826ba4cc822de0ef555bddad32
# Verified Classes:   UnreconstructableMergeError, ToolCall, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnreconstructableMergeError(RuntimeError):
    """Raised when speculative branches touched a shared resource with
    effectful calls whose causal order cannot be established at merge time."""
    pass


@dataclass
class ToolCall:
    branch_id: str
    resource: str
    kind: str            # "read" or "write"
    version: Optional[int]  # store-supplied version token, None if unsupported


@dataclass
class Branch:
    branch_id: str
    calls: list = field(default_factory=list)


def merge_speculative_branches(branches: list, checkpoint_id: str) -> dict:
    """Attempt to reconcile parallel speculative branches into one committed
    trajectory. Raises UnreconstructableMergeError instead of guessing when
    effectful sibling calls cannot be causally ordered."""
    by_resource = {}
    for b in branches:
        for c in b.calls:
            by_resource.setdefault(c.resource, []).append(c)

    committed = {}
    for resource, calls in by_resource.items():
        writes = [c for c in calls if c.kind == "write"]
        reads = [c for c in calls if c.kind == "read"]

        # Invariant 1: read-only access is always mergeable.
        if not writes:
            committed[resource] = {"mode": "read_only",
                                   "observed": [c.version for c in reads]}
            continue

        # Invariant 2/3: writes must carry version tokens so a total order exists.
        if any(w.version is None for w in writes):
            raise UnreconstructableMergeError(
                f"resource {resource!r} has effectful writes without version "
                f"tokens from branches "
                f"{sorted({w.branch_id for w in writes})}; cannot order sibling "
                f"observations relative to checkpoint {checkpoint_id}. "
                f"Roll back to checkpoint and re-fork with concurrency tokens."
            )

        # Writes have versions; ensure no two branches wrote the same version
        # (last-write-wins collision that the store silently accepted).
        versions = [w.version for w in writes]
        if len(set(versions)) != len(versions):
            raise UnreconstructableMergeError(
                f"resource {resource!r} received concurrent writes at the same "
                f"version {sorted(versions)}; store applied last-write-wins and "
                f"the losing branch's reads are causally orphaned. "
                f"Roll back to checkpoint {checkpoint_id}."
            )

        # Reconstruct: replay writes in version order, then re-derive reads.
        ordered = sorted(writes, key=lambda w: w.version)
        committed[resource] = {
            "mode": "replayed",
            "write_order": [(w.branch_id, w.version) for w in ordered],
            "final_version": ordered[-1].version,
        }

    return {"checkpoint": checkpoint_id, "committed": committed}
