# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-commit-has-outrun-its-causal-dependency-frontier.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-commit-has-outrun-its-causal-dependency-frontier.warrant.json
# Markdown SHA-256:   daadc9b4a4b1a65f17e0b71578dc8055aa425596f9c0ccfdd3c96f21aa61db74
# Code AST SHA-256:   c4a98bbf519a4567b083e2904a61cd610426b384f81d23013383595427797726
# Verified Classes:   BranchState, CausalFrontierViolation, Branch, SpeculativeOrchestrator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class BranchState(Enum):
    SPECULATING = "SPECULATING"
    COMMITTED = "COMMITTED"
    ROLLED_BACK = "ROLLED_BACK"


class CausalFrontierViolation(RuntimeError):
    """Raised when a speculative commit outruns its causal dependency frontier."""


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.SPECULATING
    # Sibling writes this branch's plan read, captured per step.
    deps: Set[str] = field(default_factory=set)
    verifier_ok: bool = False


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

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

    def commit(self, branch_id: str) -> None:
        b = self.branches[branch_id]
        if not b.verifier_ok:
            raise CausalFrontierViolation(
                f"{branch_id}: commit attempted with failed local verifier"
            )
        # Atomic frontier evaluation: snapshot sibling states, then commit.
        unresolved = {
            d for d in b.deps
            if self.branches[d].state is not BranchState.COMMITTED
        }
        if unresolved:
            raise CausalFrontierViolation(
                f"{branch_id}: causal frontier unresolved at commit; "
                f"dependencies {sorted(unresolved)} are not COMMITTED. "
                f"Local verifier success does not imply global admissibility."
            )
        b.state = BranchState.COMMITTED

    def rollback(self, branch_id: str) -> None:
        b = self.branches[branch_id]
        b.state = BranchState.ROLLED_BACK
        # Cascade: any committed branch whose frontier contains b is orphaned.
        for other in self.branches.values():
            if other.state is BranchState.COMMITTED and branch_id in other.deps:
                raise CausalFrontierViolation(
                    f"{other.branch_id}: committed branch orphaned by rollback of "
                    f"{branch_id}; re-derive from last common checkpoint."
                )

    def audit(self) -> None:
        for b in self.branches.values():
            if b.state is BranchState.COMMITTED:
                for d in b.deps:
                    if self.branches[d].state is not BranchState.COMMITTED:
                        raise CausalFrontierViolation(
                            f"post-commit audit: {b.branch_id} committed but "
                            f"depends on {d} in state {self.branches[d].state}"
                        )
