# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-a-task-branch-and-the-merge-gate-validates-against-a-stale-world-state-snapshot.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-a-task-branch-and-the-merge-gate-validates-against-a-stale-world-state-snapshot.warrant.json
# Markdown SHA-256:   8bb4b75f1f591648a9ccf1f58dfa9a51d8fb02f889faf9c2dc6f50a242b9f272
# Code AST SHA-256:   8b64e5983e203d737cc16d60c84a9261c955595dea077df49ddd2e97cb6b7c28
# Verified Classes:   StaleSnapshotMergeError, Branch, World
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class StaleSnapshotMergeError(RuntimeError):
    """Raised when a branch's validated snapshot no longer matches the live world."""
    pass


@dataclass
class Branch:
    branch_id: str
    validated_against: str          # world hash at validation time
    semantic_keys: frozenset[str]   # keys this branch's effects touch
    postcondition: dict


@dataclass
class World:
    state: dict = field(default_factory=dict)

    def hash(self) -> str:
        # Deterministic hash over sorted keys; in practice a Merkle root.
        h = hashlib.sha256()
        for k in sorted(self.state):
            h.update(f"{k}={self.state[k]};".encode())
        return h.hexdigest()


def merge_branch(world: World, branch: Branch, ledger: list) -> None:
    live = world.hash()

    # Invariant 1: apply-time CAS. The branch was validated against a
    # snapshot; if the world has moved, that validation is void.
    if live != branch.validated_against:
        ledger.append({
            "branch": branch.branch_id,
            "decision": "refused",
            "reason": "stale_snapshot",
            "validated_against": branch.validated_against,
            "applied_at": live,
        })
        raise StaleSnapshotMergeError(
            f"branch {branch.branch_id} validated against {branch.validated_against[:12]} "
            f"but world is {live[:12]}; re-fork required"
        )

    # Invariant 2: semantic key ownership. Refuse if any key this branch
    # touches was already committed by another branch since fork.
    committed = {k for entry in ledger if entry["decision"] == "merged"
                 for k in entry.get("keys", [])}
    overlap = branch.semantic_keys & committed
    if overlap:
        ledger.append({
            "branch": branch.branch_id,
            "decision": "refused",
            "reason": "semantic_key_conflict",
            "keys": sorted(overlap),
        })
        raise StaleSnapshotMergeError(
            f"branch {branch.branch_id} touches already-committed keys: {sorted(overlap)}"
        )

    # Invariant 3: validate the composed post-state, not the diff alone.
    proposed = dict(world.state)
    proposed.update(branch.postcondition)
    if proposed.get("retry_backoff_s", 0) > proposed.get("timeout_s", 10**9):
        raise StaleSnapshotMergeError(
            f"branch {branch.branch_id} would compose an invalid state: "
            f"backoff {proposed['retry_backoff_s']}s exceeds timeout {proposed['timeout_s']}s"
        )

    world.state = proposed
    ledger.append({
        "branch": branch.branch_id,
        "decision": "merged",
        "keys": sorted(branch.semantic_keys),
        "applied_at": world.hash(),
    })
