# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-branch-fan-out-before-rollback-becomes-non-invertible-in-multi-agent-plan-divergence.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-branch-fan-out-before-rollback-becomes-non-invertible-in-multi-agent-plan-divergence.warrant.json
# Markdown SHA-256:   65e0a95a22f50b8e17e16137e0d6f86e8ac0ded38dd73ebeb7f3fc9f741b7be3
# Code AST SHA-256:   015e82082bb5c944232908baa22cd3e4faaad22270e3ec09887064e074f042b7
# Verified Classes:   NonInvertibleRollbackError, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class NonInvertibleRollbackError(RuntimeError):
    """Raised when a rollback is attempted on a branch whose effects were
    emitted without a write-ahead effect log, forcing reconstruction from
    checkpoint state that cannot uniquely identify the effect."""
    pass


class Branch:
    def __init__(self, branch_id: str, effect_log: list[dict] | None = None):
        self.branch_id = branch_id
        # Write-ahead log: appended BEFORE the external effect is emitted.
        # Each entry must carry a compensation key (txn_id, idempotency_key).
        self.effect_log = effect_log or []
        self.effect_epoch = 0  # increments on first external emission

    def emit_effect(self, effect: dict) -> None:
        if "compensation_key" not in effect:
            raise NonInvertibleRollbackError(
                f"branch {self.branch_id}: effect emitted without write-ahead "
                f"compensation key; rollback would require reconstruction"
            )
        self.effect_log.append(effect)  # write-ahead
        self.effect_epoch += 1
        # ... external emission follows here ...


def rollback_branch(branch: Branch, checkpoint_only: bool) -> None:
    if branch.effect_epoch == 0:
        return  # pure context restore, invertible

    if checkpoint_only or not branch.effect_log:
        # The failure mode: rollback executor seeded from checkpoint C,
        # not from the branch's effect log. It will reconstruct effects
        # from amount/description and may match the wrong transaction.
        raise NonInvertibleRollbackError(
            f"branch {branch.branch_id} has {branch.effect_epoch} emitted "
            f"effect(s) but rollback was invoked without its effect log; "
            f"compensation would be reconstructed from checkpoint state "
            f"and is not provably bound to the original effect"
        )

    # Correct path: invert the exact logged effects, idempotently.
    for effect in reversed(branch.effect_log):
        _compensate(effect["compensation_key"])  # idempotent by key


def fan_out(branches: list[Branch], max_emitting: int = 1) -> None:
    emitting = [b for b in branches if b.effect_epoch > 0]
    if len(emitting) > max_emitting:
        raise NonInvertibleRollbackError(
            f"{len(emitting)} branches past first effect; fan-out bound is "
            f"{max_emitting}. Serialize effect-emitting branches behind the "
            f"commit gate or run them in dry-run mode."
        )
