# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-branch-pruning-when-parallel-plan-tree-agents-share-a-non-monotonic-scoring-oracle.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-branch-pruning-when-parallel-plan-tree-agents-share-a-non-monotonic-scoring-oracle.warrant.json
# Markdown SHA-256:   65dcefc6182eb5d78b329902de8461c31890ef850a9a4db838853aa1d22a5042
# Code AST SHA-256:   9bc52f7a1aea2be41f3622adce7b9fc89801d2a6685ad80c8a7d2eed43b5cc89
# Verified Classes:   PruneInvariantViolation, OracleKind, Branch, PruneController
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class PruneInvariantViolation(RuntimeError):
    """Raised when a speculative prune would destroy state before scoring stability."""


class OracleKind(Enum):
    DETERMINISTIC_VERIFIER = "deterministic_verifier"
    LLM_JUDGE_PARTIAL = "llm_judge_partial"
    LLM_JUDGE_TERMINAL = "llm_judge_terminal"


@dataclass
class Branch:
    branch_id: str
    score: float
    tool_call_cycles_completed: int = 0
    has_terminal_artifact: bool = False
    state_ref: str | None = None
    terminated: bool = False


@dataclass
class PruneController:
    oracle_kind: OracleKind
    threshold: float
    checkpointing_enabled: bool
    pruned_state_refs: dict[str, str] = field(default_factory=dict)

    def _is_scoring_stable(self, branch: Branch) -> bool:
        if self.oracle_kind is OracleKind.DETERMINISTIC_VERIFIER:
            return True
        if self.oracle_kind is OracleKind.LLM_JUDGE_TERMINAL:
            return branch.has_terminal_artifact
        # LLM_JUDGE_PARTIAL: require at least one full tool-call/observation cycle
        return branch.tool_call_cycles_completed >= 1

    def prune(self, branch: Branch, checkpoint_fn: Callable[[Branch], str]) -> None:
        if branch.terminated:
            return
        if not self._is_scoring_stable(branch):
            # Deprioritize, do not terminate. Speculative prune would be irreversible.
            return
        if branch.score >= self.threshold:
            return
        if not self.checkpointing_enabled:
            if self.oracle_kind is not OracleKind.DETERMINISTIC_VERIFIER:
                raise PruneInvariantViolation(
                    f"branch {branch.branch_id}: non-monotonic oracle "
                    f"({self.oracle_kind.value}) with checkpointing disabled; "
                    f"prune would destroy unrecoverable state"
                )
            branch.terminated = True
            return
        ref = checkpoint_fn(branch)
        if not ref:
            raise PruneInvariantViolation(
                f"branch {branch.branch_id}: checkpoint_fn returned empty ref; "
                f"refusing to terminate without recoverable state"
            )
        self.pruned_state_refs[branch.branch_id] = ref
        branch.state_ref = ref
        branch.terminated = True

    def resurrect(self, branch_id: str) -> str:
        if branch_id not in self.pruned_state_refs:
            raise PruneInvariantViolation(
                f"branch {branch_id}: no checkpointed state; cannot resurrect "
                f"(state was destroyed by an unsound prune)"
            )
        return self.pruned_state_refs[branch_id]
