# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-before-it-rolls-back-the-speculative-branch-commit-order-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-before-it-rolls-back-the-speculative-branch-commit-order-invariant.warrant.json
# Markdown SHA-256:   e389a7175cbb046d2035992a069babe7edf1381b67e6be6525f12d5ea0a9ff7c
# Code AST SHA-256:   046a38d62c87250dec8c27c360c475941e23ad5b728e8594e49cf924d59fa74d
# Verified Classes:   UnreconciledRollbackError, BranchEffect
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UnreconciledRollbackError(RuntimeError):
    """Raised when a speculative branch rollback is attempted while it holds
    unverified external effects. Rollback must not proceed; reconcile instead."""
    pass


class BranchEffect:
    __slots__ = ("effect_id", "resource", "ownership_token", "verified_exclusive")

    def __init__(self, effect_id, resource, ownership_token, verified_exclusive):
        self.effect_id = effect_id
        self.resource = resource
        self.ownership_token = ownership_token
        self.verified_exclusive = verified_exclusive


def pre_rollback_gate(branch_id, effects, re_verify_ownership):
    """Re-evaluate ownership at rollback time; never trust the spawn-time cache.

    re_verify_ownership(resource, token) -> bool: reads the resource itself and
    confirms the token is still held and no external actor observed the effect.
    """
    unverified = []
    for eff in effects:
        still_exclusive = re_verify_ownership(eff.resource, eff.ownership_token)
        if not (eff.verified_exclusive and still_exclusive):
            unverified.append(eff.effect_id)

    if unverified:
        raise UnreconciledRollbackError(
            f"branch {branch_id}: refusing rollback; {len(unverified)} effect(s) "
            f"escaped isolation boundary and cannot be proven exclusive: {unverified}. "
            f"Route to reconciliation, do not issue inverse operations."
        )
    return True


def rollback_branch(branch_id, effects, re_verify_ownership, apply_inverse):
    # Gate first. If it raises, no inverse has been issued and shared state is intact.
    pre_rollback_gate(branch_id, effects, re_verify_ownership)
    for eff in effects:
        apply_inverse(eff.effect_id)
    return "reverted"
