# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branch-rollouts-before-commit-and-what-breaks-when-a-sibling-branch-s-evidence-is-treated-as-shared-state.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branch-rollouts-before-commit-and-what-breaks-when-a-sibling-branch-s-evidence-is-treated-as-shared-state.warrant.json
# Markdown SHA-256:   432bfc8f1fb5b738c11047e0eedaee7f590394242f0520678f998e9bbab97af4
# Code AST SHA-256:   9f675de9442c50c70452e2058c39e495bc9b5d892122a6a54ed9248d196fbfe3
# Verified Classes:   SpeculativeLeakError, BranchState, Branch, ReconciliationLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class SpeculativeLeakError(RuntimeError):
    """Raised when a branch commit would depend on uncommitted sibling state."""


class BranchState(Enum):
    SPECULATIVE = "speculative"
    DEFERRED = "deferred"
    COMMITTED = "committed"
    REJECTED = "rejected"


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.SPECULATIVE
    # artifacts this branch cites as evidence, mapped to producing branch id
    cited_artifacts: Dict[str, str] = field(default_factory=dict)
    produced_artifacts: Set[str] = field(default_factory=set)


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

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

    def _provenance_closure(self, branch: Branch) -> bool:
        """True iff every cited artifact originates from a committed branch
        or from the branch itself. Speculative or rejected provenance fails."""
        for artifact, producer_id in branch.cited_artifacts.items():
            if producer_id == branch.branch_id:
                continue
            producer = self.branches.get(producer_id)
            if producer is None or producer.state is not BranchState.COMMITTED:
                return False
        return True

    def _cites_rejected(self, branch: Branch) -> bool:
        for producer_id in branch.cited_artifacts.values():
            producer = self.branches.get(producer_id)
            if producer is not None and producer.state is BranchState.REJECTED:
                return True
        return False

    def validate_and_commit(self, branch_id: str, local_validation_passed: bool) -> BranchState:
        branch = self.branches[branch_id]

        if not local_validation_passed:
            branch.state = BranchState.REJECTED
            return branch.state

        if self._cites_rejected(branch):
            # evidence is known-bad; must re-run, cannot commit or defer
            branch.state = BranchState.REJECTED
            return branch.state

        if not self._provenance_closure(branch):
            # passed locally, but depends on a still-speculative sibling:
            # commit would leak speculative state into the committed plane.
            branch.state = BranchState.DEFERRED
            return branch.state

        branch.state = BranchState.COMMITTED
        return branch.state

    def rollback(self, branch_id: str) -> None:
        branch = self.branches[branch_id]
        # reference-counted: refuse to delete artifacts a committed branch cites
        for other in self.branches.values():
            if other.state is BranchState.COMMITTED:
                for artifact, producer_id in other.cited_artifacts.items():
                    if producer_id == branch_id and artifact in branch.produced_artifacts:
                        raise SpeculativeLeakError(
                            f"cannot roll back {branch_id}: committed branch "
                            f"{other.branch_id} depends on artifact {artifact!r}"
                        )
        branch.state = BranchState.REJECTED


def run_rollout() -> None:
    ledger = ReconciliationLedger()
    ledger.register(Branch("plan-A"))
    ledger.register(Branch("plan-B"))
    ledger.register(Branch("plan-C"))

    b = ledger.branches["plan-B"]
    b.produced_artifacts.add("resolver.py")

    a = ledger.branches["plan-A"]
    a.cited_artifacts["resolver.py"] = "plan-B"

    # plan-A passes its own tests but cites plan-B's speculative resolver.
    state = ledger.validate_and_commit("plan-A", local_validation_passed=True)
    assert state is BranchState.DEFERRED, "speculative leak was not caught"

    # Attempting to commit plan-A anyway must be refused by provenance closure.
    if ledger._provenance_closure(a):
        raise SpeculativeLeakError("provenance closure incorrectly satisfied")

    # plan-B is rejected; plan-A must still be deferred, never committed.
    ledger.validate_and_commit("plan-B", local_validation_passed=False)
    if ledger.branches["plan-A"].state is BranchState.COMMITTED:
        raise SpeculativeLeakError("committed branch depends on rejected sibling")
