# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-merge-speculative-branches-that-are-semantically-compatible-but-causally-divergent-and-silently-corrupt-shared-state.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-merge-speculative-branches-that-are-semantically-compatible-but-causally-divergent-and-silently-corrupt-shared-state.warrant.json
# Markdown SHA-256:   ce0c969ab11c3a24ad76b4823e710937234f86fccd5ea058490231e7893ecc43
# Code AST SHA-256:   0d7dc41f5613f7e47ccc65d70a38afe207274b08f36c23cd86d7d890503e6f7e
# Verified Classes:   CausalMergeViolation, Branch
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class CausalMergeViolation(RuntimeError):
    """Raised when a semantically-clean merge has a dangling causal dependency."""
    pass


@dataclass
class Branch:
    name: str
    # fact_id -> version hash actually read by this branch
    read_set: Dict[str, str]
    # fact_id -> version hash that each committed step's precondition requires
    step_preconditions: Dict[str, str] = field(default_factory=dict)
    side_effecting: bool = False


def merge_speculative_branches(committed: list[Branch], discarded: list[Branch]) -> Dict[str, str]:
    """
    Merge branches that passed semantic conflict resolution.
    Enforces the causal invariant: the union read-set must satisfy every
    committed step precondition, and no committed step may depend on a fact
    version that only a discarded branch read.
    """
    if any(b.side_effecting for b in committed):
        raise CausalMergeViolation(
            "side-effecting branch cannot be semantically merged; must commit/rollback as a unit"
        )

    union_reads: Dict[str, str] = {}
    for b in committed:
        for fact_id, version in b.read_set.items():
            existing = union_reads.get(fact_id)
            if existing is not None and existing != version:
                raise CausalMergeViolation(
                    f"read-set divergence on {fact_id!r}: {existing} vs {version} "
                    f"across committed branches {b.name!r}"
                )
            union_reads[fact_id] = version

    # dependency closure: every precondition must be satisfied by the union read-set
    for b in committed:
        for fact_id, required_version in b.step_preconditions.items():
            have = union_reads.get(fact_id)
            if have is None:
                # precondition references a fact no committed branch read.
                # check whether a discarded branch is the only source of it.
                orphaned_by = [d.name for d in discarded if fact_id in d.read_set]
                raise CausalMergeViolation(
                    f"committed branch {b.name!r} depends on {fact_id!r} "
                    f"which is absent from union read-set; "
                    f"only discarded branches read it: {orphaned_by}"
                )
            if have != required_version:
                raise CausalMergeViolation(
                    f"committed branch {b.name!r} precondition on {fact_id!r} "
                    f"requires version {required_version!r} but union read-set has {have!r}"
                )

    return union_reads


# Reproduction of the observed trace:
branch_a = Branch(
    name="A",
    read_set={"customer.tier": "v1-gold"},
    step_preconditions={"customer.tier": "v1-gold"},
)
branch_b = Branch(
    name="B",
    read_set={"customer.tier": "v2-silver", "billing.ledger": "v7"},
    step_preconditions={"customer.tier": "v2-silver"},
)
branch_c = Branch(
    name="C",
    read_set={"support.history": "v3", "customer.tier": "v2-silver"},
    step_preconditions={"customer.tier": "v2-silver"},  # escalation cites the downgrade
)

try:
    # A and C passed pairwise semantic merge; B was discarded by tie-break.
    merge_speculative_branches(committed=[branch_a, branch_c], discarded=[branch_b])
except CausalMergeViolation as exc:
    print(f"merge aborted at commit gate: {exc}")
    raise
