# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-prune-a-speculative-branch-whose-tool-calls-have-already-produced-externally-observable-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-prune-a-speculative-branch-whose-tool-calls-have-already-produced-externally-observable-side-effects.warrant.json
# Markdown SHA-256:   1d3ac1c0d4c97ac22896be401dff452a4c7b0b121f2aa046c3528a584d6c8d8c
# Code AST SHA-256:   cfd5b094fdbebdf8458e437c8c79be0dcb4ad411b5901af3b5e76db5915309f3
# Verified Classes:   PruneViolation, EffectState, EffectEntry, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class PruneViolation(RuntimeError):
    """Raised when a speculative branch is pruned while holding live, non-compensable effects."""
    pass


class EffectState(Enum):
    EMPTY = "empty"
    COMPENSABLE = "compensable"
    NON_COMPENSABLE = "non_compensable"
    UNKNOWN = "unknown"  # ledger missing or written post-return


@dataclass
class EffectEntry:
    logical_step_id: str
    idempotency_token: str
    state: EffectState
    inverse_acknowledged: bool = False


@dataclass
class Branch:
    branch_id: str
    ledger: dict[str, EffectEntry] = field(default_factory=dict)
    memory: dict = field(default_factory=dict)


def record_effect_intent(branch: Branch, step_id: str, token: str, state: EffectState) -> None:
    # MUST be called before tool dispatch, not after return.
    branch.ledger[step_id] = EffectEntry(step_id, token, state)


def prune_branch(branch: Branch, deadline_exceeded: bool = False) -> None:
    if not branch.ledger:
        # No effects recorded. Safe to prune *only if* we trust the ledger is complete.
        # A missing ledger for a branch that made tool calls is UNKNOWN, not empty.
        branch.memory.clear()
        return

    for step_id, entry in branch.ledger.items():
        if entry.state is EffectState.EMPTY:
            continue
        if entry.state is EffectState.COMPENSABLE and entry.inverse_acknowledged:
            continue
        # NON_COMPENSABLE, UNKNOWN, or compensable-but-unacknowledged:
        # the branch is committed-speculative. Pruning would orphan a live effect.
        if deadline_exceeded:
            raise PruneViolation(
                f"branch {branch.branch_id} step {step_id} held {entry.state.value} "
                f"effect past quarantine deadline; escalate to merge-or-promote"
            )
        raise PruneViolation(
            f"refusing to prune branch {branch.branch_id}: step {step_id} is "
            f"{entry.state.value} (inverse_acknowledged={entry.inverse_acknowledged}); "
            f"quarantine and reconcile before discarding memory"
        )

    branch.memory.clear()


def select_and_prune(winner: Branch, losers: list[Branch], deadline_exceeded: bool = False) -> None:
    quarantined = []
    for loser in losers:
        try:
            prune_branch(loser, deadline_exceeded=deadline_exceeded)
        except PruneViolation:
            quarantined.append(loser.branch_id)
    if quarantined:
        # Do not silently proceed. The winner's plan must be reconciled against
        # the quarantined branches' ledgers, or duplicate effects will land.
        raise PruneViolation(
            f"cannot finalize selection: branches {quarantined} are committed-speculative; "
            f"reconcile idempotency tokens against winner {winner.branch_id} before resume"
        )
