# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-sub-agent-spawn-when-the-orchestrator-s-cost-pruning-budget-is-invalidated-mid-fanout.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-sub-agent-spawn-when-the-orchestrator-s-cost-pruning-budget-is-invalidated-mid-fanout.warrant.json
# Markdown SHA-256:   865709e66d006dbd3fc557aef5093511be5ab2f4f6ed856f5d08d9b052ffdb14
# Code AST SHA-256:   f4ffc32888e8ddf3b0f3156e2456da8d0ecd97d405438ce04be5b40bedf73234
# Verified Classes:   InvalidatedBudgetError, SpeculativeOrchestrator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class InvalidatedBudgetError(RuntimeError):
    """Raised when pruning/backfill is attempted against a cost basis that has diverged past its validity band."""
    pass


DIVERGENCE_CEILING = 1.5


class SpeculativeOrchestrator:
    def __init__(self, committed_budget: float, estimator_covers_nested: bool):
        self.committed_budget = committed_budget
        self.estimator_covers_nested = estimator_covers_nested
        self.realized_cost = 0.0
        self.estimated_cost = 0.0

    def budget_is_valid(self) -> bool:
        if not self.estimator_covers_nested:
            # Unmetered nested spawns make every prune decision unsound.
            return False
        if self.estimated_cost <= 0:
            return True
        return (self.realized_cost / self.estimated_cost) <= DIVERGENCE_CEILING

    def prune(self, child_id: str, marginal_value: float, marginal_cost: float) -> str:
        if not self.budget_is_valid():
            raise InvalidatedBudgetError(
                f"refusing to prune {child_id}: cost basis invalidated "
                f"(realized={self.realized_cost:.4f}, estimated={self.estimated_cost:.4f}, "
                f"nested_metered={self.estimator_covers_nested}). "
                f"Freeze pruning; drain in-flight children and reconcile."
            )
        if marginal_value > marginal_cost:
            return f"pruned {child_id}"
        return f"kept {child_id}"

    def backfill(self, slice_id: str) -> str:
        if not self.budget_is_valid():
            raise InvalidatedBudgetError(
                f"refusing to backfill {slice_id}: backfill against invalidated budget "
                f"compounds overrun. Abort and report."
            )
        return f"spawned replacement for {slice_id}"


def run_fanout(orch: SpeculativeOrchestrator, children: list[dict]) -> list[str]:
    outcomes: list[str] = []
    for child in children:
        try:
            outcomes.append(
                orch.prune(child["id"], child["marginal_value"], child["marginal_cost"])
            )
        except InvalidatedBudgetError as exc:
            outcomes.append(f"FROZEN: {exc}")
            break
    return outcomes
