# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-sub-budgets-when-a-parent-agent-s-sla-clock-and-a-child-s-token-quota-drift-out-of-phase.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-sub-budgets-when-a-parent-agent-s-sla-clock-and-a-child-s-token-quota-drift-out-of-phase.warrant.json
# Markdown SHA-256:   24f7138f1ae74006d93f47ae91416cadc1fffaa009ca00d71775c973dfc36d9e
# Code AST SHA-256:   cfbb5afd720ef69a7694bd5cb5eb309c85e4693df8586d416fd9bb45e1650a57
# Verified Classes:   BudgetReconciliationError, SLAViolationError, ChildLedger, ParentLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class BudgetReconciliationError(RuntimeError):
    """Raised when a parent cannot reconcile a child's consumed quota against its grant."""


class SLAViolationError(RuntimeError):
    """Raised when a delegation decision would push the parent past its upstream deadline."""


@dataclass
class ChildLedger:
    granted: int
    consumed: int = 0
    last_checkpoint: int = 0          # monotonic, updated on every tool call
    terminal_status: Optional[str] = None  # SUCCESS | QUOTA_EXHAUSTED | DEADLINE_EXCEEDED | CRASHED
    partial_state_fraction: float = 0.0


@dataclass
class ParentLedger:
    ceiling: int
    reserved: int = 0
    min_viable_sub_budget: int = 15_000
    min_viable_child_latency_s: float = 8.0

    def free(self) -> int:
        return self.ceiling - self.reserved


def reclaim(child: ChildLedger) -> int:
    """Quota a returned child hands back to the parent, independent of status."""
    if child.terminal_status is None:
        raise BudgetReconciliationError(
            f"child not terminal; cannot reclaim (granted={child.granted})"
        )
    if child.terminal_status == "CRASHED":
        # No final consumption report; bound true consumption from below by checkpoint.
        consumed = max(child.consumed, child.last_checkpoint)
    else:
        consumed = child.consumed
    if consumed > child.granted:
        raise BudgetReconciliationError(
            f"child over-consumed: {consumed} > granted {child.granted}"
        )
    return child.granted - consumed


def should_redelegate(
    parent: ParentLedger,
    child: ChildLedger,
    sla_remaining_s: float,
    salvage_threshold: float = 0.3,
) -> bool:
    if sla_remaining_s < parent.min_viable_child_latency_s:
        # Not enough SLA left to be worth a fresh child; abandon and report.
        return False
    available = parent.free() + reclaim(child)
    if available < parent.min_viable_sub_budget:
        return False
    if child.partial_state_fraction < salvage_threshold:
        return False
    return True


def reconcile_and_decide(
    parent: ParentLedger,
    children: list[ChildLedger],
    sla_remaining_s: float,
) -> list[ChildLedger]:
    """Refund reclaimable quota for all terminal children, then decide re-delegation."""
    for c in children:
        if c.terminal_status is None:
            continue
        parent.reserved -= reclaim(c)
    if parent.reserved < 0:
        raise BudgetReconciliationError(
            f"reserved went negative ({parent.reserved}); ledger double-refunded"
        )
    to_redelegate = [
        c for c in children
        if c.terminal_status != "SUCCESS" and should_redelegate(parent, c, sla_remaining_s)
    ]
    if not to_redelegate and parent.free() < parent.min_viable_sub_budget:
        raise SLAViolationError(
            f"no re-delegation possible and free budget {parent.free()} below minimum; "
            f"parent must return INSUFFICIENT_BUDGET with {sla_remaining_s:.1f}s SLA unspent"
        )
    return to_redelegate
