# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-a-speculative-branch-that-has-already-been-committed-by-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-a-speculative-branch-that-has-already-been-committed-by-consensus.warrant.json
# Markdown SHA-256:   b11a8066e064aba10f24d3ee03b57be165c7aac4a069ffe32b89181090197efd
# Code AST SHA-256:   2ab8676c2353d409608d14516a3a51560463282e7b126dd2971309670b11d831
# Verified Classes:   UnsafePruneError, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnsafePruneError(RuntimeError):
    """Raised when a branch is about to be pruned while it holds
    un-reclaimed non-idempotent effects. Pruning here would orphan
    external state that no committed trajectory owns."""
    pass


class Branch:
    def __init__(self, branch_id, effect_frontier_empty=True,
                 reclamation_handles=None, in_flight_effects=0):
        self.branch_id = branch_id
        self.effect_frontier_empty = effect_frontier_empty
        self.reclamation_handles = reclamation_handles or []
        self.in_flight_effects = in_flight_effects
        self.state = "ACTIVE"


def prune_branch(branch, commit_log):
    """Prune a losing branch ONLY if its effects are fenced and reclaimable.
    Otherwise quarantine: keep the accounting record alive and route any
    reclamation through the consensus log as a separate committed step."""
    if branch.state != "ACTIVE":
        raise UnsafePruneError(
            f"branch {branch.branch_id} is {branch.state}, not ACTIVE"
        )

    if not branch.effect_frontier_empty:
        # A non-idempotent call has been issued since the last checkpoint.
        # Pruning now can race a late response landing after the vote closed.
        if branch.in_flight_effects > 0 or not branch.reclamation_handles:
            branch.state = "QUARANTINED"
            commit_log.append({
                "op": "quarantine",
                "branch": branch.branch_id,
                "reason": "unreclaimed_non_idempotent_effect",
            })
            raise UnsafePruneError(
                f"branch {branch.branch_id} has {branch.in_flight_effects} "
                f"in-flight effect(s) and {len(branch.reclamation_handles)} "
                f"reclamation handle(s); quarantined instead of pruned"
            )

    # Safe path: frontier empty, or all effects fenced with durable handles.
    branch.state = "PRUNED"
    commit_log.append({
        "op": "prune",
        "branch": branch.branch_id,
        "reclaim": list(branch.reclamation_handles),
    })
    return branch.state
