# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-speculative-branch-pruning-collapse-when-parallel-plan-tree-agents-share-a-monotone-confidence-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-speculative-branch-pruning-collapse-when-parallel-plan-tree-agents-share-a-monotone-confidence-ledger.warrant.json
# Markdown SHA-256:   11b26abcd77313c341ff7f3a7634bc675fd0091e9b2f0be64936779895dd0c07
# Code AST SHA-256:   5b1302e32dfcae78ec2de7ffc3cc276d4b48aedfe58a9dc5c9f6b66174427186
# Verified Classes:   SpeculativePruneCollapse, BranchEmission, PruneLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass, field
from typing import Dict, List, Optional


class SpeculativePruneCollapse(RuntimeError):
    """Raised when a ledger-prune decision compares incommensurable branch evidence."""
    pass


@dataclass
class BranchEmission:
    branch_id: str
    step: int
    raw_confidence: float
    confidence_fn_id: str          # identifies the branch's heuristic scale
    calibrated: bool = False


@dataclass
class PruneLedger:
    high_water: float = 0.0
    high_water_step: int = -1
    high_water_fn: Optional[str] = None
    high_water_branch: Optional[str] = None
    tau: float = 0.25
    k_min: int = 3
    history: List[BranchEmission] = field(default_factory=list)

    def emit(self, e: BranchEmission) -> None:
        self.history.append(e)
        # Only update the mark from calibrated, synchronized emissions.
        if not e.calibrated:
            return
        if e.raw_confidence > self.high_water:
            self.high_water = e.raw_confidence
            self.high_water_step = e.step
            self.high_water_fn = e.confidence_fn_id
            self.high_water_branch = e.branch_id

    def should_prune(self, e: BranchEmission) -> bool:
        # Guard 1: no pruning before schedule artifacts wash out.
        if e.step < self.k_min:
            return False
        # Guard 2: refuse to compare uncalibrated evidence to the ledger.
        if not e.calibrated:
            raise SpeculativePruneCollapse(
                f"branch {e.branch_id} emitted uncalibrated confidence "
                f"(fn={e.confidence_fn_id}) but ledger comparison was attempted"
            )
        # Guard 3: refuse cross-scale comparison.
        if self.high_water_fn is not None and self.high_water_fn != e.confidence_fn_id:
            raise SpeculativePruneCollapse(
                f"cross-scale prune: branch {e.branch_id} fn={e.confidence_fn_id} "
                f"vs high-water fn={self.high_water_fn} set by "
                f"{self.high_water_branch} at step {self.high_water_step}"
            )
        # Guard 4: refuse to compare a branch against a mark set at a later step
        # (the mark must be causally prior and at an equal or earlier step).
        if self.high_water_step > e.step:
            raise SpeculativePruneCollapse(
                f"non-causal prune: high-water step {self.high_water_step} "
                f"> branch step {e.step} for {e.branch_id}"
            )
        return (self.high_water - e.raw_confidence) > self.tau


def orchestrate_prune(ledger: PruneLedger, emissions: List[BranchEmission]) -> Dict[str, str]:
    """Return branch_id -> 'kept' | 'pruned' | 're-admitted'."""
    decisions: Dict[str, str] = {}
    pruned: Dict[str, BranchEmission] = {}
    for e in sorted(emissions, key=lambda x: (x.step, x.branch_id)):
        try:
            prune = ledger.should_prune(e)
        except SpeculativePruneCollapse:
            # Fail closed: do not prune on incommensurable evidence.
            decisions[e.branch_id] = "kept"
            continue
        if prune:
            decisions[e.branch_id] = "pruned"
            pruned[e.branch_id] = e
        else:
            decisions[e.branch_id] = "kept"
        ledger.emit(e)

    # Re-admission: if the surviving leader is the only kept branch and it
    # shares the high-water mark, re-admit the best pruned branch from checkpoint.
    kept = [b for b, d in decisions.items() if d == "kept"]
    if len(kept) == 1 and pruned:
        best_pruned = max(pruned.values(), key=lambda e: e.raw_confidence)
        decisions[best_pruned.branch_id] = "re-admitted"

    if not kept:
        raise SpeculativePruneCollapse("all branches pruned; no survivor to verify")
    return decisions
