# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-commits-when-a-rollback-invalidates-a-peer-s-predicted-continuation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-commits-when-a-rollback-invalidates-a-peer-s-predicted-continuation.warrant.json
# Markdown SHA-256:   cd6be1881fe19b64d1c5cf9d93b2c09e0f80275860c4896c870e851c8892e98a
# Code AST SHA-256:   ec0af6eac1d6b26cc301331220f4377f95a7360bbc5d85f2444a61719226f05f
# Verified Classes:   BranchStatus, SpeculativeCommitError, Branch, Speculator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class BranchStatus(Enum):
    PROPOSED = "proposed"
    CONFIRMED = "confirmed"
    ROLLED_BACK = "rolled_back"
    UNRESOLVED = "unresolved"  # lease expired, no CONFIRM seen


class SpeculativeCommitError(RuntimeError):
    """Raised when a speculator attempts to commit work whose read set
    includes a branch that is not provably confirmed."""


@dataclass
class Branch:
    branch_id: str
    status: BranchStatus = BranchStatus.PROPOSED
    epoch: int = 0


@dataclass
class Speculator:
    speculator_id: str
    own_branch: str
    read_set: Set[str] = field(default_factory=set)
    confirm_epoch: int = -1

    def commit(self, branches: Dict[str, Branch], current_epoch: int) -> None:
        # Own branch must be explicitly confirmed at a current epoch.
        own = branches.get(self.own_branch)
        if own is None or own.status is not BranchStatus.CONFIRMED:
            raise SpeculativeCommitError(
                f"{self.speculator_id}: own branch {self.own_branch} "
                f"status={own.status if own else 'missing'}; refusing commit"
            )
        if self.confirm_epoch < current_epoch:
            raise SpeculativeCommitError(
                f"{self.speculator_id}: stale confirm epoch "
                f"{self.confirm_epoch} < {current_epoch}; fencing required"
            )
        # Fence on the entire read set: any unresolved or rolled-back
        # dependency contaminates this output, even if own branch is fine.
        for dep_id in self.read_set:
            dep = branches.get(dep_id)
            if dep is None or dep.status is not BranchStatus.CONFIRMED:
                raise SpeculativeCommitError(
                    f"{self.speculator_id}: read-set dependency {dep_id} "
                    f"status={dep.status if dep else 'missing'}; "
                    f"output is contaminated and must be discarded"
                )


def reconcile_commit(
    speculator: Speculator,
    branches: Dict[str, Branch],
    current_epoch: int,
) -> str:
    """Entry point an instance calls at every speculative commit point."""
    speculator.commit(branches, current_epoch)
    return f"committed:{speculator.speculator_id}:{speculator.own_branch}"


# Reproduces the observed S2 failure: own branch confirmed, but its
# read-set dependency (S1's draft) was rolled back. Fencing must reject.
if __name__ == "__main__":
    branches = {
        "b7": Branch("b7", BranchStatus.ROLLED_BACK, epoch=2),
        "b8": Branch("b8", BranchStatus.CONFIRMED, epoch=2),
    }
    s2 = Speculator(
        speculator_id="S2",
        own_branch="b8",
        read_set={"b7"},          # read S1's phantom draft
        confirm_epoch=2,
    )
    try:
        reconcile_commit(s2, branches, current_epoch=2)
    except SpeculativeCommitError as e:
        print(f"fenced: {e}")
