# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-after-a-hedged-tool-call-has-already-produced-external-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-after-a-hedged-tool-call-has-already-produced-external-side-effects.warrant.json
# Markdown SHA-256:   33974bcbc9ef176edea463ef181fd598e439b9410ce1d58bd1b377032171d106
# Code AST SHA-256:   6409245fd54023e382963b472d87edb9c1624d51052612500e0a986279a492ce
# Verified Classes:   UnreconciledHedgeError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnreconciledHedgeError(RuntimeError):
    """Raised when a speculative branch has an external side effect that cannot be confirmed as rolled back."""
    pass


def rollback_branch(branch, external_state) -> str:
    """
    Attempt to roll back a speculative branch. Returns the branch's new state.
    Raises UnreconciledHedgeError if a dispatched hedge has an external effect
    that no compensating action can confirm was undone.
    """
    for call in branch.dispatched_calls:
        if not call.is_side_effecting:
            continue
        if call.compensating_action is None:
            # No way to undo: the branch is committed by side effect.
            raise UnreconciledHedgeError(
                f"branch {branch.id} dispatched non-compensable call "
                f"{call.tool}({call.args_hash}) while speculative; "
                f"cannot mark rolled_back"
            )
        receipt = call.compensating_action.execute()
        if not receipt.confirmed or not external_state.matches_expected(call, receipt):
            raise UnreconciledHedgeError(
                f"compensation for {call.tool}({call.args_hash}) on branch "
                f"{branch.id} did not confirm; external state diverges from audit log"
            )
    branch.state = "rolled_back"
    return branch.state
