# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-abort-a-speculative-branch-without-poisoning-the-committed-ledger-the-pre-commit-side-effect-leak.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-abort-a-speculative-branch-without-poisoning-the-committed-ledger-the-pre-commit-side-effect-leak.warrant.json
# Markdown SHA-256:   f60e1877e103ec4ca900eb972cb4202e979308a4473c60bee69d1df3c8acc5be
# Code AST SHA-256:   de9a43ff5905134e6bcf8681f32ebac815fa9468163cf50c7a0a9aba247c5757
# Verified Classes:   SpeculativeCommitViolation, BranchState, CommitGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SpeculativeCommitViolation(RuntimeError):
    """Raised when a side-effecting call escapes the commit-token gate."""
    pass


class BranchState:
    SPECULATIVE = "speculative"
    LIMINAL = "liminal"      # side-effecting calls queued, not yet promoted
    COMMITTED = "committed"
    ABORTED = "aborted"


class CommitGate:
    def __init__(self):
        self._branch_state = {}
        self._resource_owner = {}   # resource -> branch_id holding commit token

    def promote(self, branch_id: str, resources: list[str]) -> bool:
        # Atomic: either all resources are acquired and branch is COMMITTED,
        # or nothing changes and branch stays LIMINAL.
        if self._branch_state.get(branch_id) == BranchState.ABORTED:
            return False
        for r in resources:
            if r in self._resource_owner and self._resource_owner[r] != branch_id:
                return False
        for r in resources:
            self._resource_owner[r] = branch_id
        self._branch_state[branch_id] = BranchState.COMMITTED
        return True

    def abort(self, branch_id: str) -> None:
        state = self._branch_state.get(branch_id)
        if state == BranchState.COMMITTED:
            # Abort lost the race to promotion; must become commit-with-rollback.
            raise SpeculativeCommitViolation(
                f"abort(branch={branch_id}) after promotion: convert to ledgered rollback"
            )
        self._branch_state[branch_id] = BranchState.ABORTED

    def dispatch_side_effect(self, branch_id: str, resource: str, call) -> object:
        if self._branch_state.get(branch_id) != BranchState.COMMITTED:
            raise SpeculativeCommitViolation(
                f"side-effecting call on resource={resource} from branch={branch_id} "
                f"in state={self._branch_state.get(branch_id)}: no commit token held"
            )
        if self._resource_owner.get(resource) != branch_id:
            raise SpeculativeCommitViolation(
                f"branch={branch_id} does not own commit token for resource={resource}"
            )
        return call()


def run_branch_step(gate: CommitGate, branch_id: str, plan_step) -> object:
    if plan_step.mutates_world:
        # Provisional: queue, do not execute, until promotion.
        if gate._branch_state.get(branch_id) != BranchState.COMMITTED:
            gate._branch_state[branch_id] = BranchState.LIMINAL
            plan_step.queue()
            return None
        return gate.dispatch_side_effect(branch_id, plan_step.resource, plan_step.execute)
    return plan_step.execute()
