# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-roll-back-a-speculative-branch-the-non-idempotent-side-effect-horizon-in-branch-and-verify-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-roll-back-a-speculative-branch-the-non-idempotent-side-effect-horizon-in-branch-and-verify-multi-agent-execution.warrant.json
# Markdown SHA-256:   814006ca516c55c83b7e21429a0ea951d80e8309c4b9f6d2a278355b18fe8fed
# Code AST SHA-256:   1f15c6326d0aba1fde59d1f524e098dc2858adf4088fde5e2ea3952bcc6588a3
# Verified Classes:   SideEffectHorizonCrossed, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SideEffectHorizonCrossed(RuntimeError):
    """Raised when a branch is asked to roll back after emitting an
    externally observable, non-idempotent, uncompensated effect."""
    pass


REVOCABLE = "REVOCABLE"
IDEMPOTENT_BY_LOGICAL_KEY = "IDEMPOTENT_BY_LOGICAL_KEY"
IRREVOCABLE = "IRREVOCABLE"


class Branch:
    def __init__(self, branch_id, effects):
        # effects: list of dicts with keys: kind, logical_key, compensated
        self.branch_id = branch_id
        self.effects = effects
        self.quarantined = False

    def crossed_horizon(self):
        for e in self.effects:
            if e["kind"] == IRREVOCABLE and not e.get("compensated", False):
                return True
            if e["kind"] == IDEMPOTENT_BY_LOGICAL_KEY and e.get("physical_key_scoped"):
                # token scoped per physical call, not per logical op -> hedging orphans effects
                return True
        return False


def rollback(branch: Branch) -> str:
    if branch.crossed_horizon():
        # Refuse to erase: the effects are already in the world.
        branch.quarantined = True
        raise SideEffectHorizonCrossed(
            f"branch {branch.branch_id} crossed its side-effect horizon; "
            f"quarantine and reconcile, do not roll back"
        )
    # Safe: all effects revocable / logically idempotent / compensated.
    branch.effects.clear()
    return "ROLLED_BACK"


def commit_or_rollback(branches, committed_id):
    results = {}
    for b in branches:
        if b.branch_id == committed_id:
            results[b.branch_id] = "COMMITTED"
            continue
        try:
            results[b.branch_id] = rollback(b)
        except SideEffectHorizonCrossed as exc:
            results[b.branch_id] = f"QUARANTINED: {exc}"
    return results
