# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-merges-against-byzantine-committed-shared-memory-without-silently-adopting-a-poisoned-write.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-merges-against-byzantine-committed-shared-memory-without-silently-adopting-a-poisoned-write.warrant.json
# Markdown SHA-256:   464ea9a0cb29a78749470f5e8938e094fd10807e5d84773c99fdd95c9c57b09b
# Code AST SHA-256:   19efcc1f8016312e91d66b4ce604820af83bb596f741c7a55a21248c3c3193f7
# Verified Classes:   SpeculativeMergeConflict, VersionVector, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class SpeculativeMergeConflict(RuntimeError):
    """Raised when a speculative branch's read-set has drifted from the
    committed head between fork and merge, making its local consistency
    check unsound. The branch must be re-derived or discarded."""
    pass


@dataclass(frozen=True)
class VersionVector:
    versions: dict  # fact_key -> committed version at time of read

    def superseded_by(self, head: "VersionVector") -> set:
        """Return fact keys whose committed version advanced past our pin."""
        drifted = set()
        for key, pinned in self.versions.items():
            current = head.versions.get(key)
            if current is not None and current > pinned:
                drifted.add(key)
        return drifted


@dataclass
class Branch:
    branch_id: str
    read_set: VersionVector
    derivation: str          # e.g. "apply_discount(0.2)"
    local_check_passed: bool


def merge_branch(branch: Branch, committed_head: VersionVector) -> str:
    """Merge a speculative branch into shared memory.

    Guardrail: re-validate the branch's read-set against the CURRENT
    committed head before trusting its local consistency check. The
    local check alone is unsound under Byzantine-committed drift.
    """
    if not branch.local_check_passed:
        raise SpeculativeMergeConflict(
            f"branch {branch.branch_id} failed local consistency check"
        )

    drifted = branch.read_set.superseded_by(committed_head)
    if drifted:
        # The branch's derivation was sound against a ghost snapshot.
        # Its result must NOT be ratified: re-derive or discard.
        raise SpeculativeMergeConflict(
            f"branch {branch.branch_id} read-set drifted on {sorted(drifted)}; "
            f"local check is unsound against committed head. Re-derive required."
        )

    # Read-set is pinned to the current head: merge is safe.
    digest = hashlib.sha256(
        f"{branch.branch_id}:{branch.derivation}".encode()
    ).hexdigest()
    return digest


# --- failure trace: the observed incident ---
head_at_fork = VersionVector({"account.tier": 41})
branch_b2 = Branch(
    branch_id="B2",
    read_set=VersionVector({"account.tier": 41}),
    derivation="apply_discount(0.2)",
    local_check_passed=True,          # sound against v41 snapshot
)
# Byzantine-committed write lands while B2 is in flight:
head_at_merge = VersionVector({"account.tier": 42})  # tier flipped to silver

try:
    merge_branch(branch_b2, head_at_merge)
except SpeculativeMergeConflict as e:
    print(f"MERGE ABORTED: {e}")
    # -> branch B2 must be re-derived against v42: apply_discount(0.0)
