# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-before-its-sibling-branches-resolve-the-pre-commit-visibility-leak-in-parallel-multi-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-before-its-sibling-branches-resolve-the-pre-commit-visibility-leak-in-parallel-multi-agent.warrant.json
# Markdown SHA-256:   9f9cd4ccc47747d864373ff44003a6aab7449103f58ed4630a0f66c6f2e607b4
# Code AST SHA-256:   02a1291bd1a5cf1be39293becf1b29bc9e41772b8a2b0367c441d6eab326c12a
# Verified Classes:   SpeculationVisibilityError, ReplaySnapshotMismatch, WriteRecord, SpeculativeStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SpeculationVisibilityError(RuntimeError):
    """A surviving branch read content written by a non-committed (rolled-back) branch."""
    pass


class ReplaySnapshotMismatch(RuntimeError):
    """Auditor replay used a retrieval snapshot that includes post-fork writes."""
    pass


@dataclass
class WriteRecord:
    branch_id: str
    key: str
    value: str
    committed: bool = False


@dataclass
class SpeculativeStore:
    # All writes, tagged by originating branch.
    writes: Dict[str, WriteRecord] = field(default_factory=dict)
    # Branches whose output was committed (survive the selection barrier).
    committed_branches: Set[str] = set()
    # Branches that were rolled back; their writes must be invisible.
    rolled_back_branches: Set[str] = field(default_factory=set)
    # Fork point marker: writes after this are speculative until barrier.
    fork_epoch: int = 0
    current_epoch: int = 0

    def write(self, branch_id: str, key: str, value: str) -> None:
        self.writes[key] = WriteRecord(branch_id=branch_id, key=key, value=value)

    def rollback(self, branch_id: str) -> None:
        # Revoke visibility, not just delete artifacts. Mark all of the
        # branch's writes as rolled back so any read path refuses them.
        self.rolled_back_branches.add(branch_id)
        for rec in self.writes.values():
            if rec.branch_id == branch_id:
                rec.committed = False

    def commit(self, branch_id: str) -> None:
        self.committed_branches.add(branch_id)
        for rec in self.writes.values():
            if rec.branch_id == branch_id:
                rec.committed = True

    def read(self, reader_branch: str, key: str, *, pre_fork_only: bool = False) -> Optional[str]:
        rec = self.writes.get(key)
        if rec is None:
            return None
        # Invariant: a rolled-back branch's write is observationally equivalent
        # to a write that never happened. Any read of it is a visibility leak.
        if rec.branch_id in self.rolled_back_branches and not rec.committed:
            raise SpeculationVisibilityError(
                f"branch {reader_branch} attempted to read {key!r} written by "
                f"rolled-back branch {rec.branch_id}; speculation barrier violated"
            )
        # A surviving branch reading an uncommitted sibling's write is also a leak
        # if the barrier has not resolved (pre-fork_only enforces this).
        if pre_fork_only and rec.branch_id not in self.committed_branches:
            raise SpeculationVisibilityError(
                f"pre-fork read of {key!r} by {reader_branch} surfaced uncommitted "
                f"branch {rec.branch_id}"
            )
        return rec.value


def audit_replay(store: SpeculativeStore, candidate_branch: str, keys: list[str]) -> Dict[str, str]:
    # The auditor must replay against a pre-fork snapshot, NOT the live retrieval
    # state. If it reads the live store, it reproduces contamination and certifies it.
    if store.current_epoch != store.fork_epoch:
        raise ReplaySnapshotMismatch(
            f"auditor replay at epoch {store.current_epoch} but fork was at "
            f"{store.fork_epoch}; replay is not causally independent of live writes"
        )
    out: Dict[str, str] = {}
    for k in keys:
        v = store.read(candidate_branch, k, pre_fork_only=True)
        if v is not None:
            out[k] = v
    return out


# --- failure trace reproduction ---
store = SpeculativeStore()
store.fork_epoch = 0
store.current_epoch = 0

store.write("B", "note_column_x_nullable", "Column X is nullable; skip backfill.")
store.rollback("B")                       # B fails audit, rolled back
store.commit("A")                         # A is the selected branch

# A's surviving loop retrieves B's ghost note -> must raise, not silently inherit.
try:
    store.read("A", "note_column_x_nullable")
except SpeculationVisibilityError as e:
    print("BLOCKED:", e)

# Auditor replaying A against the live (post-fork) store would certify the
# contaminated result; the guard rejects the replay instead.
store.current_epoch = 1
try:
    audit_replay(store, "A", ["note_column_x_nullable"])
except ReplaySnapshotMismatch as e:
    print("REPLAY REJECTED:", e)
