# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-transitively-attenuated-aaif-warrant-when-the-delegation-depth-exceeds-the-issuer-s-re-delegation-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-transitively-attenuated-aaif-warrant-when-the-delegation-depth-exceeds-the-issuer-s-re-delegation-budget.warrant.json
# Markdown SHA-256:   428e208d38d53853043abb99e88b72bc3d7f949adcff5d4d115a31dea4235765
# Code AST SHA-256:   7cc2625f7041cb29018765d6115ef719ee877951adf0f867cbbe65587e200368
# Verified Classes:   DelegationBudgetExhausted, DelegationBudgetLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class DelegationBudgetExhausted(RuntimeError):
    """Raised when a parent warrant has no remaining re-delegation budget,
    or when the issuer's budget ledger shows the budget was already consumed
    (replay / retry fork). Delegation must fail closed; execution may proceed."""


class DelegationBudgetLedger:
    """Authoritative, atomic budget store at the issuer. Keyed on
    (parent_warrant_id, delegation_request_id) for idempotent replay."""

    def __init__(self):
        self._consumed = {}  # parent_warrant_id -> set of request_ids
        self._minted = {}    # (parent_warrant_id, request_id) -> child_warrant

    def mint_child(self, parent, request_id, child_agent_id, child_scope):
        if parent.redelegate_remaining <= 0:
            raise DelegationBudgetExhausted(
                f"parent {parent.warrant_id} has redelegate_remaining=0; "
                f"execution-valid but delegation-invalid"
            )
        key = (parent.warrant_id, request_id)
        if key in self._minted:
            # Idempotent replay: return the previously minted child, do NOT fork.
            return self._minted[key]
        spent = self._consumed.setdefault(parent.warrant_id, set())
        if len(spent) >= parent.redelegate_remaining:
            raise DelegationBudgetExhausted(
                f"parent {parent.warrant_id} budget already exhausted by "
                f"{len(spent)} prior delegations; refusing to fork"
            )
        if not child_scope.issubset(parent.scope):
            raise DelegationBudgetExhausted(
                "child scope is not a subset of parent scope"
            )
        child = ChildWarrant(
            warrant_id=f"{parent.warrant_id}:{request_id}",
            scope=child_scope,
            redelegate_remaining=parent.redelegate_remaining - 1,
            expires_at=min(parent.expires_at, child_scope.expires_at),
        )
        spent.add(request_id)
        self._minted[key] = child
        return child
