# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-irreversible-side-effect-leakage-in-speculative-multi-agent-branches-before-rollback-reconciliation-completes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-irreversible-side-effect-leakage-in-speculative-multi-agent-branches-before-rollback-reconciliation-completes.warrant.json
# Markdown SHA-256:   6c54a6671ead1fcf084cbb33e9858051ac85d55d632ee49377825a6f41683723
# Code AST SHA-256:   a99ada8a06b2e32d79bb745199319cdf0f6fdaa535462f5cd1328321d71f3d71
# Verified Classes:   IrreversibleEffectLeak
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class IrreversibleEffectLeak(RuntimeError):
    """Raised when a branch is about to be rolled back while it holds
    committed, uncompensated, irreversible side effects."""
    pass


EFFECT_REVERSIBLE = "REVERSIBLE"
EFFECT_IRREVERSIBLE = "IRREVERSIBLE"


def rollback_branch(branch, commit_log, quiescence_watermark):
    """
    branch: has .status, .ledger (list of calls with .effect_class,
            .compensation_handle, .idempotency_key, .acked_at)
    commit_log: shared log of effect confirmations
    quiescence_watermark: timestamp after which no confirmation may be pending
    """
    # Signal 1: status says discardable, but ledger holds live irreversibles.
    for call in branch.ledger:
        if call.effect_class == EFFECT_IRREVERSIBLE:
            if call.compensation_handle is None and call.idempotency_key is None:
                raise IrreversibleEffectLeak(
                    f"branch {branch.id} call {call.tool} is IRREVERSIBLE "
                    f"with no compensation handle and no idempotency key; "
                    f"cannot discard without effect leakage"
                )

    # Signal 2: unacknowledged in-flight call at transition time.
    for call in branch.ledger:
        if call.acked_at is None:
            raise IrreversibleEffectLeak(
                f"branch {branch.id} call {call.tool} has no terminal "
                f"acknowledgment; effect state is indeterminate"
            )

    # Signal 3: late-arriving confirmations postdating rollback initiation.
    late = [
        c for c in commit_log.confirmations_for(branch.id)
        if c.timestamp > quiescence_watermark
    ]
    if late:
        raise IrreversibleEffectLeak(
            f"branch {branch.id} has {len(late)} effect confirmations "
            f"arriving after rollback watermark; rollback would race the "
            f"external system"
        )

    # Safe: every effect is reversible, acknowledged, and quiescent.
    branch.status = "discarded"
    return branch
