# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-aaif-credential-whose-delegation-chain-is-length-valid-but-scope-monotonicity-violating-at-the-t.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-aaif-credential-whose-delegation-chain-is-length-valid-but-scope-monotonicity-violating-at-the-t.warrant.json
# Markdown SHA-256:   9b12b8cfd0c4543807ac1fe568b3cfd9bad60f89a276db23676a6e7908534c68
# Code AST SHA-256:   9b77f413e352281ed45c3b0a7b518eb80f90d55b9cbe6fce42df31a14a41e086
# Verified Classes:   ScopeMonotonicityViolation, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ScopeMonotonicityViolation(RuntimeError):
    """Raised when a delegated warrant exceeds the delegator's live remaining budget."""
    pass


@dataclass(frozen=True)
class Warrant:
    action_scope: frozenset
    budget_ceiling: int
    consumed: int = 0

    @property
    def remaining(self) -> int:
        return self.budget_ceiling - self.consumed


def validate_exchange(parent: Warrant, child: Warrant, live_remaining: int | None) -> None:
    # Action scope must be a subset at every hop.
    if not child.action_scope <= parent.action_scope:
        raise ScopeMonotonicityViolation(
            f"action scope {child.action_scope} not subset of {parent.action_scope}"
        )

    # Fail closed if the authoritative ledger is unreachable.
    if live_remaining is None:
        raise ScopeMonotonicityViolation(
            "live budget ledger unreachable; refusing to validate against declared ceiling"
        )

    # The invariant: child ceiling bounded by parent's LIVE remainder, not its grant.
    if child.budget_ceiling > live_remaining:
        raise ScopeMonotonicityViolation(
            f"child budget_ceiling={child.budget_ceiling} exceeds "
            f"parent live remaining={live_remaining} "
            f"(parent declared ceiling={parent.budget_ceiling}, consumed={parent.consumed})"
        )
