# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-speculative-branch-whose-rollback-was-shadowed-by-a-committed-sibling-write.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-speculative-branch-whose-rollback-was-shadowed-by-a-committed-sibling-write.warrant.json
# Markdown SHA-256:   47b9f9a52a0b052b845f900bb1f373b596260c1969e9213df34e4285965e886f
# Code AST SHA-256:   37f0530382bcab2f09a1357051833c424d1efa4d1e86780e3e426779cb8372a9
# Verified Classes:   ShadowedRollbackError, BranchState, ReadRecord, Branch, Reconciler
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ShadowedRollbackError(RuntimeError):
    """Raised when a rollback would leave a committed sibling dependent on a reverted speculative value."""
    pass


class BranchState(Enum):
    SPECULATING = "speculating"
    PROVISIONAL = "provisional"   # has speculative-read deps, cannot commit yet
    COMMITTED = "committed"
    ROLLED_BACK = "rolled_back"
    INVALIDATED = "invalidated"   # dependency rolled back; must re-execute


@dataclass
class ReadRecord:
    resource: str
    producer: str | None  # None => base/pre-fork value; else branch id of speculative writer


@dataclass
class Branch:
    bid: str
    writes: Set[str] = field(default_factory=set)
    reads: list[ReadRecord] = field(default_factory=list)
    state: BranchState = BranchState.SPECULATING

    def speculative_deps(self) -> Set[str]:
        return {r.producer for r in self.reads if r.producer is not None}


class Reconciler:
    def __init__(self) -> None:
        self.branches: Dict[str, Branch] = {}

    def register(self, b: Branch) -> None:
        self.branches[b.bid] = b

    def commit(self, bid: str) -> None:
        b = self.branches[bid]
        unresolved = {
            p for p in b.speculative_deps()
            if self.branches[p].state not in (BranchState.COMMITTED,)
        }
        if unresolved:
            # Commit would freeze a value whose producer may still roll back.
            b.state = BranchState.PROVISIONAL
            raise ShadowedRollbackError(
                f"branch {bid} cannot commit: holds speculative-read deps on "
                f"unresolved producers {sorted(unresolved)}"
            )
        b.state = BranchState.COMMITTED

    def rollback(self, bid: str) -> None:
        b = self.branches[bid]
        # Find every branch that read a value this branch speculatively wrote.
        dependents = [
            other.bid for other in self.branches.values()
            if other.bid != bid and bid in other.speculative_deps()
        ]
        committed_dependents = [
            d for d in dependents
            if self.branches[d].state == BranchState.COMMITTED
        ]
        if committed_dependents:
            # Rolling back now would shadow a committed read: the dependent's
            # artifact already encodes a value about to vanish. Refuse and
            # force invalidation instead of a silent, "successful" rollback.
            for d in committed_dependents:
                self.branches[d].state = BranchState.INVALIDATED
            b.state = BranchState.ROLLED_BACK
            raise ShadowedRollbackError(
                f"rollback of {bid} shadowed by committed dependents "
                f"{sorted(committed_dependents)}; marked INVALIDATED for re-execution"
            )
        # No committed reader: safe to revert and invalidate provisional readers.
        for d in dependents:
            if self.branches[d].state in (BranchState.PROVISIONAL, BranchState.SPECULATING):
                self.branches[d].state = BranchState.INVALIDATED
        b.state = BranchState.ROLLED_BACK


def reconcile_fork(reconciler: Reconciler, winner: str, loser: str) -> None:
    """Commit the winner, roll back the loser, in an order that respects read provenance."""
    # Commit the winner first only if it has no dep on the loser; otherwise the
    # commit() guard will raise and force re-execution, which is the correct outcome.
    reconciler.commit(winner)
    reconciler.rollback(loser)
