# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-parallel-branch-has-already-committed-irreversible-side-effects-before-rollback-arbitration-completes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-parallel-branch-has-already-committed-irreversible-side-effects-before-rollback-arbitration-completes.warrant.json
# Markdown SHA-256:   685beba0e928c378c5b67a544410de5c921b2e383402453c9f03723b2c08ca76
# Code AST SHA-256:   d45e9f2900026154ab7157d65f6bbdc3b042f272d4c8d5d91807d358a949ae4a
# Verified Classes:   UnrollableBranchError, EffectReceipt, Branch, ReceiptStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional

class UnrollableBranchError(RuntimeError):
    """Raised when a branch marked for rollback has already committed an external effect."""
    pass

@dataclass
class EffectReceipt:
    intent_hash: str
    tool: str
    target: str
    committed_at: Optional[float]  # None => reservation held, not committed

@dataclass
class Branch:
    branch_id: str
    intent_hash: str
    plan: list[tuple[str, str]]  # (tool, target)
    status: str = "running"

class ReceiptStore:
    def __init__(self) -> None:
        self._receipts: list[EffectReceipt] = []

    def record(self, r: EffectReceipt) -> None:
        self._receipts.append(r)

    def committed_for(self, intent_hash: str) -> list[EffectReceipt]:
        return [r for r in self._receipts
                if r.intent_hash == intent_hash and r.committed_at is not None]

def rollback_branch(branch: Branch, store: ReceiptStore, now: float) -> None:
    """Roll back a losing speculative branch. Refuses if any effect already committed."""
    committed = store.committed_for(branch.intent_hash)
    if committed:
        branch.status = "rollback_blocked"
        raise UnrollableBranchError(
            f"branch {branch.branch_id} (intent {branch.intent_hash[:8]}) "
            f"cannot roll back: {len(committed)} committed effect(s) already "
            f"escaped to external systems: "
            f"{[(r.tool, r.target, r.committed_at) for r in committed]}"
        )
    # Safe path: only reservations exist; release them, discard context delta.
    for tool, target in branch.plan:
        store.record(EffectReceipt(branch.intent_hash, tool, target, committed_at=None))
    branch.status = "rolled_back"
    _ = now  # reservation release is modeled by absence of commit timestamp
