# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-speculative-branch-before-rollback-rather-than-replaying-it-the-side-effect-witness-problem-in-branch.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-speculative-branch-before-rollback-rather-than-replaying-it-the-side-effect-witness-problem-in-branch.warrant.json
# Markdown SHA-256:   b693b7cd15a55741e06066e782f796063a8781c7109e571bd69fe2e1ff638f7e
# Code AST SHA-256:   e45b27b5c0179ac23fe9fd4ea446b5072c34db1e3564343bb1217f8dcdd15cb4
# Verified Classes:   PoisonedSpeculativeBranch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class PoisonedSpeculativeBranch(RuntimeError):
    """Raised when a losing branch cannot be safely rolled back or replayed."""


def rollback_branch(branch, ledger, checkpoint):
    effects = ledger.committed_effects(branch.id)

    if not effects:
        return checkpoint.truncate_to(branch.fork_span)

    unsafe = [
        e for e in effects
        if not e.idempotent and e.compensating_action is None
    ]
    if unsafe:
        # Invalidate, do not replay. Compensate and quarantine.
        for e in unsafe:
            if e.compensating_action is None:
                raise PoisonedSpeculativeBranch(
                    f"branch {branch.id} emitted non-idempotent effect "
                    f"{e.tool}@{e.idempotency_key} with no inverse; "
                    f"replay would duplicate it"
                )
        ledger.mark_poisoned(branch.id)
        return checkpoint.truncate_to(branch.fork_span, exclude_effects=effects)

    # All effects idempotent under their keys: replay is safe.
    return checkpoint.truncate_to(branch.fork_span)
