# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-fan-out-when-branch-pruning-cost-estimates-become-self-referential.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-fan-out-when-branch-pruning-cost-estimates-become-self-referential.warrant.json
# Markdown SHA-256:   c72fd41aed10f6bd46abc25372eb3d1cd1786d88c4ffc23407dd40ca726edb16
# Code AST SHA-256:   31bb6f2c5085f6fbf0ac56f7c879af17ddf6a92a50282aa79136c1744f2def2e
# Verified Classes:   LedgerContaminatedEstimate, Branch, Orchestrator
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class LedgerContaminatedEstimate(RuntimeError):
    """Raised when a branch's cost estimate changes without its state changing,
    indicating the estimator reads the global budget ledger and has entered the
    self-referential pruning regime."""
    pass


@dataclass
class Branch:
    branch_id: str
    state_digest: str          # hash of the branch's own working state
    cost_estimate: float       # must be a function of state_digest ONLY


@dataclass
class Orchestrator:
    branches: list[Branch]
    last_rank: dict[str, int] = field(default_factory=dict)

    def check_invariant(self, current: list[Branch]) -> None:
        """Detect state-preserving rank inversions between rounds."""
        ranked = sorted(current, key=lambda b: b.cost_estimate)
        new_rank = {b.branch_id: i for i, b in enumerate(ranked)}
        by_id = {b.branch_id: b for b in current}

        for a_id, ra in self.last_rank.items():
            for b_id, rb in self.last_rank.items():
                if a_id == b_id or a_id not in new_rank or b_id not in new_rank:
                    continue
                # states must be unchanged for this to be a violation
                if by_id[a_id].state_digest != self._prev_digest(a_id):
                    continue
                if by_id[b_id].state_digest != self._prev_digest(b_id):
                    continue
                inverted = (ra < rb and new_rank[a_id] > new_rank[b_id])
                if inverted:
                    raise LedgerContaminatedEstimate(
                        f"rank inversion between {a_id} and {b_id} with unchanged "
                        f"state digests; estimator reads remaining_budget. "
                        f"Abort fan-out and fall back to sequential plan."
                    )
        self.last_rank = new_rank
        self._prev_digests = {b.branch_id: b.state_digest for b in current}

    def _prev_digest(self, branch_id: str) -> str | None:
        return getattr(self, "_prev_digests", {}).get(branch_id)

    def prune_and_select(self, current: list[Branch], budget: float) -> Branch:
        self.check_invariant(current)
        ranked = sorted(current, key=lambda b: b.cost_estimate)
        cumulative = 0.0
        for b in ranked:
            cumulative += b.cost_estimate
            if cumulative > 0.8 * budget:
                break
            winner = b
        return winner
