# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-branch-before-the-divergence-oracle-has-resolved.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-branch-before-the-divergence-oracle-has-resolved.warrant.json
# Markdown SHA-256:   55f787f4225d638845eb18af5344332c9e62d470326a1cdfd96d178fade79444
# Code AST SHA-256:   afe90936a6a982eed4080a396d89a7063a3b80c0928e43354edc40f7df66ed33
# Verified Classes:   SpeculativeCommitViolation, Branch, SpeculationLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeCommitViolation(RuntimeError):
    """Raised when a speculative branch commits an effect before its
    divergence oracle has resolved it as the winner."""
    pass


class Branch:
    def __init__(self, branch_id: str, speculation_id: str):
        self.branch_id = branch_id
        self.speculation_id = speculation_id
        self.reserved: list[str] = []
        self.committed: list[str] = []


class SpeculationLedger:
    def __init__(self):
        self.oracle_state: dict[str, str] = {}       # speculation_id -> PENDING|RESOLVED
        self.winner: dict[str, str | None] = {}      # speculation_id -> branch_id

    def resolve(self, speculation_id: str, winner_branch: str) -> None:
        self.oracle_state[speculation_id] = "RESOLVED"
        self.winner[speculation_id] = winner_branch

    def commit(self, branch: Branch, effect_id: str) -> None:
        state = self.oracle_state.get(branch.speculation_id, "PENDING")
        winner = self.winner.get(branch.speculation_id)
        if state != "RESOLVED" or winner != branch.branch_id:
            # The gate that should have blocked this. If we reach here, a
            # branch leaked an irreversible effect before resolution.
            raise SpeculativeCommitViolation(
                f"branch {branch.branch_id} attempted commit of {effect_id} "
                f"under speculation {branch.speculation_id} "
                f"(oracle_state={state}, winner={winner}). "
                f"Effect is now durable and rollback degrades to compensation."
            )
        branch.committed.append(effect_id)


def run_speculative_step(branch: Branch, ledger: SpeculationLedger,
                         effect_id: str, irreversible: bool) -> None:
    if irreversible and ledger.oracle_state.get(branch.speculation_id) != "RESOLVED":
        # Correct behavior: defer irreversible tail until resolution.
        raise SpeculativeCommitViolation(
            f"irreversible effect {effect_id} requested by branch "
            f"{branch.branch_id} before oracle resolution; defer to post-resolve."
        )
    ledger.commit(branch, effect_id)
