# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-forks-a-speculative-branch-and-the-replay-log-diverges-at-a-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-forks-a-speculative-branch-and-the-replay-log-diverges-at-a-tool-call-boundary.warrant.json
# Markdown SHA-256:   2186223e2dc8c3165ea0ee8737e3f0a7f3543ceccf0075e9fbe0e2ab912bdefe
# Code AST SHA-256:   9eb2be815411369d456556655842d1ddde6585611b0b0b709a4c85c59ab9c9de
# Verified Classes:   SpeculativeIsolationViolation, Branch, ForkTopology
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Hashable


class SpeculativeIsolationViolation(RuntimeError):
    """Raised when a branch reads a key under a sibling's uncommitted write."""


@dataclass
class Branch:
    branch_id: str
    pending_writes: set[Hashable] = field(default_factory=set)
    committed: bool = False
    aborted: bool = False


@dataclass
class ForkTopology:
    branches: dict[str, Branch] = field(default_factory=dict)

    def live_siblings(self, branch_id: str) -> list[Branch]:
        return [
            b for b in self.branches.values()
            if b.branch_id != branch_id and not b.committed and not b.aborted
        ]

    def guard_read(self, branch_id: str, key: Hashable, tool_is_snapshot_isolated: bool) -> None:
        if tool_is_snapshot_isolated:
            return
        for sibling in self.live_siblings(branch_id):
            if key in sibling.pending_writes:
                raise SpeculativeIsolationViolation(
                    f"branch {branch_id} read key {key!r} while sibling "
                    f"{sibling.branch_id} holds an uncommitted write to it; "
                    f"log segment is not a valid replay artifact"
                )

    def guard_irreversible_effect(self, branch_id: str, tool: str, reversible: bool, deferrable: bool) -> None:
        if reversible or deferrable:
            return
        branch = self.branches[branch_id]
        if not branch.committed:
            raise SpeculativeIsolationViolation(
                f"branch {branch_id} invoked irreversible tool {tool!r} before commit; "
                f"rollback cannot undo it"
            )


def execute_branch_read(topology: ForkTopology, branch_id: str, key: Hashable,
                        tool_is_snapshot_isolated: bool = False) -> None:
    topology.guard_read(branch_id, key, tool_is_snapshot_isolated)


def execute_branch_effect(topology: ForkTopology, branch_id: str, tool: str,
                          reversible: bool = False, deferrable: bool = False) -> None:
    topology.guard_irreversible_effect(branch_id, tool, reversible, deferrable)


# Reproduction of the observed trace.
topo = ForkTopology()
topo.branches["B1"] = Branch("B1")
topo.branches["B2"] = Branch("B2")
topo.branches["B1"].pending_writes.add("incident:4471:owner")

execute_branch_read(topo, "B2", "incident:4471:owner")  # raises: sibling write visible
