# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-context-budget-starvation-is-being-inherited-rather-than-caused-nested-subagent-fan-out-under-hierarchical-memory-han.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-context-budget-starvation-is-being-inherited-rather-than-caused-nested-subagent-fan-out-under-hierarchical-memory-han.warrant.json
# Markdown SHA-256:   3a229151a09b9f800e83f838570d8d507c24cddc854d8ff3deecb0001ccd97dd
# Code AST SHA-256:   022f3bb21ad76b30168ae1f62b2990111f7eaeca8f1effbfc0874417f57d6b55
# Verified Classes:   InheritedStarvationError, Budget, MemorySlice
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class InheritedStarvationError(RuntimeError):
    """Raised when a handoff would pre-consume the receiver's working budget."""
    pass


@dataclass
class Budget:
    window: int
    min_working_set: int
    safety_margin: int = 2048


@dataclass
class MemorySlice:
    inherited_tokens: int   # provenance-tagged, immutable in receiver
    authored_tokens: int    # distilled by the immediate sender

    @property
    def total(self) -> int:
        return self.inherited_tokens + self.authored_tokens

    @property
    def inherited_ratio(self) -> float:
        return self.inherited_tokens / self.total if self.total else 0.0


INHERITED_RATIO_CAP = 0.40


def validate_handoff(slice_: MemorySlice, receiver: Budget) -> None:
    usable = receiver.window - receiver.min_working_set - receiver.safety_margin
    if slice_.total > usable:
        raise InheritedStarvationError(
            f"handoff slice {slice_.total} exceeds receiver usable budget {usable} "
            f"(window={receiver.window}, min_working_set={receiver.min_working_set}); "
            f"re-distill against receiver task or escalate for re-allocation"
        )
    if slice_.inherited_ratio > INHERITED_RATIO_CAP:
        raise InheritedStarvationError(
            f"inherited_ratio {slice_.inherited_ratio:.2f} > cap {INHERITED_RATIO_CAP}; "
            f"sender must re-distill inherited memory for receiver task, not pass through"
        )


def dispatch(parent_remaining: int, receiver: Budget, ratio: float = 0.25) -> MemorySlice:
    # Defective ratio arithmetic retained only to demonstrate the trigger.
    naive = int(parent_remaining * ratio)
    # Contract-based sizing: receiver requirement is the ceiling.
    usable = receiver.window - receiver.min_working_set - receiver.safety_margin
    authored = min(naive, int(usable * (1 - INHERITED_RATIO_CAP)))
    inherited = min(int(usable * INHERITED_RATIO_CAP), naive - authored)
    slice_ = MemorySlice(inherited_tokens=inherited, authored_tokens=authored)
    validate_handoff(slice_, receiver)
    return slice_
