# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-fence-speculative-side-effects-before-a-parallel-branch-rollback-can-be-trusted.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-fence-speculative-side-effects-before-a-parallel-branch-rollback-can-be-trusted.warrant.json
# Markdown SHA-256:   3d5851fc9905c069648f7eef24c9837ab65931f944e2d29fd0dc03eab4c00d0e
# Code AST SHA-256:   52eb3cc47eca95b3c7a07b4fe43ae464611cc3ccbfe68063e8d8cfeb0fd674ee
# Verified Classes:   UnfencedSpeculativeEffect, EffectClass, Branch, SpeculativeOrchestrator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnfencedSpeculativeEffect(RuntimeError):
    """Raised when a speculative branch's effect cannot be proven rolled back."""
    pass


class EffectClass:
    PURE = "pure"            # deterministic, no external state touched
    STATEFUL = "stateful"    # mutates resource, advances cursor, or consumes budget


class Branch:
    def __init__(self, branch_id, fencing_token):
        self.branch_id = branch_id
        self.fencing_token = fencing_token
        self.state = "SPECULATIVE"
        self.pending_calls = {}


class SpeculativeOrchestrator:
    def __init__(self, remote):
        self.remote = remote

    def dispatch(self, branch, call, effect_class):
        # Fence must be attached before the call leaves the process.
        if effect_class == EffectClass.STATEFUL and not branch.fencing_token:
            raise UnfencedSpeculativeEffect(
                f"branch {branch.branch_id}: stateful call {call['id']} "
                f"dispatched without fencing token"
            )
        ack = self.remote.dispatch(call, branch.fencing_token, effect_class)
        branch.pending_calls[call["id"]] = ack
        return ack

    def rollback(self, branch):
        # Rollback is only valid if every stateful call is acknowledged-terminal.
        for call_id, ack in branch.pending_calls.items():
            if not ack.terminal:
                raise UnfencedSpeculativeEffect(
                    f"branch {branch.branch_id}: cannot roll back, call {call_id} "
                    f"is in-flight; effect may apply after rollback"
                )
        self.remote.invalidate_fence(branch.fencing_token)
        branch.state = "ROLLED_BACK"

    def commit(self, branch):
        # Two-phase: prepare, then apply, with remote acknowledgment.
        prepared = self.remote.prepare(branch.fencing_token)
        if not prepared.ok:
            raise UnfencedSpeculativeEffect(
                f"branch {branch.branch_id}: prepare failed, state may have diverged"
            )
        applied = self.remote.apply(branch.fencing_token)
        if not applied.acknowledged:
            raise UnfencedSpeculativeEffect(
                f"branch {branch.branch_id}: apply unacknowledged, "
                f"commit recorded against unverified state"
            )
        branch.state = "COMMITTED"
