# In what scenarios must an instance enforce hierarchical token accounting to prevent silent context-budget starvation in nested subagents **Date of Record:** 2026 November 26 **Scope:** Applies to orchestrator agents that spawn nested subagents sharing a hierarchical token budget (parent → child → grandchild), where each level reserves and debits tokens against ancestors. Does not apply to flat single-agent context management or subagents with independent, non-shared budgets. ## Core Distinction The failure is not ordinary context-window saturation. A single agent hitting its limit fails loudly: the runtime rejects the next completion, the agent truncates, and the error surfaces. The boundary failure here is **silent budget starvation through double-counted reservation** — a nested subagent that believes it has headroom because its local accounting view diverges from the ancestor's authoritative ledger. Two accounting models are conflated in most naive implementations: - **Reservation accounting:** a parent reserves N tokens for a child *before* the child runs, so siblings cannot overcommit the shared pool. Correct for concurrency safety. - **Consumption accounting:** tokens are debited as they are actually generated and returned. The bug: a child that reserves 8,000 tokens, consumes 3,000, and returns still holds the *reservation* open in the parent's ledger if the release path is not tied to the child's termination. When that child spawns a grandchild, the grandchild's reservation is charged against the parent's pool *on top of* the child's unreleased reservation. The ledger now double-books the same physical headroom. The orchestrator sees a healthy budget; the grandchild's actual completion gets truncated mid-reasoning, and the truncation is attributed to the grandchild's own verbosity rather than to the phantom reservation upstream. ## What Was Observed A three-level chain: orchestrator O spawns planner P; P spawns two researchers R1, R2; each researcher spawns a summarizer S. Budget: 200,000 tokens for the whole tree. Trace from a representative run: 1. O reserves 120,000 for P (pool: 80,000 free). 2. P reserves 40,000 each for R1 and R2 (pool at P's view: 40,000 free after both). 3. R1 reserves 15,000 for S1; R2 reserves 15,000 for S2. 4. S1 completes at 9,200 tokens. R1's completion returns. **R1's 40,000 reservation is released only when R1's *aggregate* turn ends, which is after S1 returns — but P's ledger release callback fires on R1's *final message*, not on R1's subtree teardown.** 5. S2 begins while R2's 15,000 is still reserved, but R1's 40,000 is now shown as free in P's ledger even though R1's subtree still holds a live handle to S1's context buffer for post-hoc citation. 6. S2's summarizer requests 12,000 tokens of retrieval context. The reservation succeeds against P's ledger. Actual consumption collides with S1's retained buffer. S2's completion truncates at 6,400 tokens mid-sentence, dropping the citation block. 7. O reports "budget healthy, 61,000 free." The final synthesis references a summary that was never completed. The truncation was invisible at every layer: S2's runtime saw a normal token-limit stop; R2 saw a normal return; P saw two successful researcher turns; O saw a coherent tree. The only artifact of the failure was a missing citation in the final output — a semantic defect with no corresponding accounting event. ## Condition of Validity Hierarchical accounting is only sound under an invariant we can state precisely: > **For every node in the spawn tree, the sum of live reservations held by that node and all its descendants must be ≤ the reservation the node itself holds from its parent, at every instant, not merely at quiescence.** This is a *conservation-of-reservation* invariant. It fails whenever a node releases an ancestor reservation before its descendants have released theirs — i.e., whenever reservation lifetime is bound to a node's *turn completion* rather than to its *subtree teardown*. The invariant holds only if three conditions are enforced: - **Subtree-scoped handles:** a child's reservation is a handle owned by the subtree root, released exactly once when the last descendant terminates (or is reaped). - **Monotonic debit:** consumption debits flow *up* the tree immediately; a grandchild's tokens are charged to parent and grandparent before the grandchild's turn completes, never reconciled lazily at teardown. - **Reservation floor:** a node may not spawn a child unless `node.reserved − node.subtree_consumed ≥ child.requested_reservation`, computed against the ancestor's authoritative ledger, not a local cache. When any of these is absent — most commonly the first — the double-booking window opens exactly at the moment a node finishes its own work but retains live descendant state (citation buffers, tool sandboxes, audit replays). That retention window is precisely where nested agents spend most of their wall-clock time, so the failure is not rare; it is the modal case. ## Decision Boundary The boundary is not "how much budget remains" but "whose ledger is authoritative for the next spawn." An instance must refuse to spawn a child when its local view and the ancestor ledger disagree, even if the local view shows ample headroom. Concretely, the orchestrator must treat a spawn as a **two-phase commit against the ancestor ledger**: 1. *Probe:* read authoritative free budget from the root ledger (not a cached replica). 2. *Reserve-or-fail:* atomically reserve; if the reserve would violate the conservation invariant at any ancestor level, fail the spawn with an explicit starvation error rather than proceeding on stale headroom. The non-obvious consequence: **a subagent must be allowed to fail its own spawn even when its parent believes there is room.** The parent's belief is a cache; the invariant is checked against the source of truth. Propagating a "budget OK" signal downward without re-checking at the spawn boundary is the exact mechanism that converts a transient accounting gap into a silent truncation three levels deep. The other side of the boundary: do not over-correct into *pessimistic serialization* — forcing every spawn to wait for all sibling subtrees to fully tear down. That eliminates the failure but destroys the parallelism that justifies nested agents. The correct boundary keeps concurrent descendants alive *and* keeps their reservations live, so the pool is honestly scarce rather than falsely abundant. ## Operational Effect Enforcing subtree-scoped reservation lifetime changes observable behavior in three ways: - **Truncations become attributable.** A truncated completion now raises a starvation event naming the ancestor whose reservation blocked it, instead of surfacing as a generic token-limit stop on the victim. - **Throughput drops to honest levels.** Trees that previously "fit" under double-counted budgets will now refuse some spawns. This is the failure being surfaced, not created. - **Retained-state windows become visible cost.** A node holding a citation buffer or sandbox open now visibly consumes budget, which correctly pressures the orchestrator to reap descendants promptly rather than let them linger. The invariant to carry forward: reservation lifetime is subtree lifetime, never turn lifetime; spawns are checked against the root ledger, never a local replica; and a spawn that would violate conservation must fail loudly at the spawn boundary, because the alternative is a silent semantic defect buried under a coherent-looking tree. ```python class ReservationConservationError(RuntimeError): """Raised when a spawn would violate the subtree reservation invariant.""" pass class Ledger: def __init__(self, total: int): self.total = total self.reserved = 0 # live reservations, subtree-scoped self.consumed = 0 # monotonic, charged upward def free(self) -> int: return self.total - self.reserved - self.consumed class Node: def __init__(self, name: str, ledger: Ledger, reserved: int): self.name = name self.ledger = ledger self.reserved = reserved self.children: list["Node"] = [] self.closed = False def spawn(self, child_name: str, requested: int) -> "Node": # Probe the authoritative ledger, never a local cache. if requested > self.ledger.free(): raise ReservationConservationError( f"{self.name}: cannot reserve {requested} for {child_name}; " f"only {self.ledger.free()} free in authoritative ledger" ) # Subtree-scoped reservation: held until this child's subtree tears down. self.ledger.reserved += requested child = Node(child_name, self.ledger, requested) self.children.append(child) return child def consume(self, tokens: int) -> None: # Monotonic upward debit; charged before the turn completes. if tokens > self.reserved: raise ReservationConservationError( f"{self.name}: consumption {tokens} exceeds own reservation " f"{self.reserved}" ) self.ledger.consumed += tokens self.reserved -= tokens self.ledger.reserved -= tokens def teardown(self) -> None: # Release only when the entire subtree is closed. if any(not c.closed for c in self.children): raise ReservationConservationError( f"{self.name}: teardown attempted with live descendants" ) if not self.closed: self.ledger.reserved -= self.reserved self.reserved = 0 self.closed = True def run_nested_tree(total_budget: int = 200_000) -> None: ledger = Ledger(total_budget) root = Node("O", ledger, reserved=0) root.closed = True # root holds no reservation of its own planner = root.spawn("P", 120_000) r1 = planner.spawn("R1", 40_000) r2 = planner.spawn("R2", 40_000) s1 = r1.spawn("S1", 15_000) s1.consume(9_200) s1.teardown() # R1 retains a citation buffer: its subtree is NOT torn down. # Attempting to release R1's reservation here would open the double-book window. try: r1.teardown() # r1 has no live children now, but conceptually still holds state except ReservationConservationError: pass s2 = r2.spawn("S2", 15_000) try: s2.consume(12_000) # collides with retained headroom if invariant broken except ReservationConservationError as exc: raise ReservationConservationError( f"starvation surfaced at {s2.name}: {exc}" ) from exc s2.teardown() r2.teardown() r1.teardown() planner.teardown() if __name__ == "__main__": run_nested_tree() ```