# How should an instance attribute observability cost across a nested agent tree when per-tool budget enforcement and trace-span fan-out disagree **Date of Record:** 2026 November 28 **Scope:** Applies to hierarchical agent systems where a parent instance spawns child instances (sub-agents, tool-calling workers, or MCP-delegated sessions) and where observability spans are emitted per LLM call and per tool invocation under a shared budget ledger. Does not apply to single-instance flat tool loops with no delegated child sessions, nor to billing reconciliation performed offline against provider invoices. ## Core Distinction Two accounting surfaces observe the same work but count it differently, and the divergence is the failure. The **budget ledger** decrements at the moment a call is *authorized*: the parent reserves tokens/cost against a per-tool and per-subtree ceiling before dispatch, then settles on completion. It is a *reservation* system — monotonic, conservative, and keyed by the authorizing instance. The **observability trace** records spans at the moment a call *completes*, keyed by the emitting instance, with parent-span linkage reconstructed from propagated context headers. It is an *eventual* system — permissive, additive, and keyed by whoever actually ran the work. The invariant that silently breaks: **for every dollar the ledger reserves, exactly one trace span must eventually settle it, and the sum of child reservations must equal the parent's reservation for that subtree.** When a child instance re-emits, retries, or fans out a tool call whose span is attributed to the child while the budget was reserved against the parent, the two surfaces drift. The drift is not a rounding error — it is a *structural* mismatch that compounds with tree depth, because each nesting level re-parents the span without re-parenting the reservation. ## What Was Observed A three-level tree: orchestrator `O` → planner `P` → executor `E`, each a distinct LLM instance with its own context window. `O` reserved a subtree budget of 200k tokens for `P`. `P` reserved 60k to `E` for a retrieval tool call. `E`'s tool call timed out at the transport layer (no response within the A2A deadline), but the underlying retrieval backend *did* execute and bill. `E` retried once. The retry succeeded. Two spans were emitted: `span(E,tool,attempt=1,status=timeout)` and `span(E,tool,attempt=2,status=ok)`, both linked to `P`'s span as parent. The ledger saw: `P` reserved 60k, `E` settled 60k on the *successful* attempt, and the timed-out attempt was refunded to `P`'s subtree balance because the reservation was released on timeout. But the backend billed for both attempts. The trace showed 120k of tool work attributed under `P`; the ledger showed 60k reserved and 60k settled. The 60k gap — the timed-out-but-billed attempt — was orphaned: it existed in the trace, had no corresponding ledger entry, and was attributed to `P`'s subtree by span linkage while the actual cost was incurred by `E`'s transport retry. At depth three this orphan was invisible. At depth five, with three tool types each exhibiting ~4% timeout-retry rates, the orphaned trace volume exceeded the settled ledger volume by 18%, and cost attribution by subtree was wrong by more than the entire budget of the smallest leaf. The orchestrator's chargeback report and the platform's invoice disagreed, and neither was wrong — they were measuring different events. ## Condition of Validity The reservation-equals-settlement invariant holds **only if** every dispatched call has a terminal ledger event whose idempotency key matches exactly one terminal trace span, *including* attempts that were billed but not acknowledged. It fails under three precise conditions, any one of which is sufficient: 1. **Transport-level timeout with backend-side execution.** The caller releases the reservation; the callee bills. No terminal ledger event exists for the billed work. 2. **Retry fan-out under a single reservation.** The reservation is keyed to the logical call, but the trace emits one span per physical attempt. Reservation count = 1, span count = N. 3. **Cross-instance re-parenting on delegation.** When `P` delegates to `E` via A2A/MCP, the propagated trace context sets `E`'s span parent to `P`, but the budget reservation remains keyed to `P`'s authorizing identity. If `E` is itself the emitter of a child span for a grandchild, the grandchild's cost is attributed up the *span* tree while reserved down the *identity* tree — and these trees diverge the moment any node is a shared or pooled worker serving multiple parents. The invariant is **not** restored by increasing timeout budgets, by adding retries, or by sampling. Sampling makes it worse: sampled traces under-count orphaned attempts non-uniformly, so the attribution error is no longer even a stable bias you can correct for. ## Decision Boundary The boundary is: **does the system treat a reservation release as proof of non-execution?** If yes — the common design, where `finally: ledger.release(key)` runs on any exception including timeout — the system assumes the callee did not bill. This is false for any transport where dispatch and execution are not atomically observable by the caller. The boundary must move to: a reservation is released only on a *confirmed-negative* terminal signal (explicit rejection, connection refused before dispatch, 4xx from the callee's admission layer). On timeout, ambiguous disconnect, or deadline expiry, the reservation must transition to a **quarantine state** — held, not released, not settled — until a reconciliation pass matches it against the callee's emitted span or an explicit absence-of-span after a settle window. The guardrail invariant: **no reservation may transition to `released` without a matching terminal span, and no span may transition to `settled` without a matching reservation.** The two surfaces are joined by an idempotency key derived from `(authorizing_instance_id, logical_call_id, attempt_epoch)` — where `attempt_epoch` is monotonic per logical call, so retries share a `logical_call_id` but differ in epoch, and the ledger is allowed exactly one settled epoch per logical call while the trace is allowed N attempt spans that must *all* map to that one settlement (with the non-settled attempts marked `billed_unacknowledged`). Per-tool budget enforcement must therefore enforce against **reserved + quarantined**, never against settled-only. Enforcing against settled-only lets a retry storm of timed-out-but-billed calls blow through the tool ceiling by the retry multiplier before any settlement is visible. ## Operational Effect With the quarantine-and-reconcile guardrail, the failure trace changes as follows. On `E`'s timeout, the 60k reservation enters `quarantined` keyed to `(P, call_7, epoch=1)`. `E`'s retry reserves a *second* 60k at `(P, call_7, epoch=2)`. The tool ceiling for `P` now sees 120k committed, not 60k, and enforcement triggers correctly if the ceiling is 100k. On successful retry, epoch=2 settles. The reconciliation pass, after the settle window, finds epoch=1 has a trace span with `status=timeout` but no settlement; it transitions epoch=1 from `quarantined` to `billed_unacknowledged`, attributes the cost to `P`'s subtree (matching the span), and emits a reconciliation discrepancy record. The orchestrator's chargeback now equals the invoice, because the orphan is *named* rather than dropped. The residual cost is latency: quarantined reservations hold budget for the settle window, so a tool with a 30s deadline and a 60s settle window effectively reduces usable ceiling by up to 2x under retry load. This is the correct trade — the alternative is silent attribution drift that scales with tree depth and retry rate, and that is undetectable from either surface alone. ```python from dataclasses import dataclass, field from enum import Enum from typing import Dict, Optional class AttributionInvariantError(RuntimeError): """Raised when ledger and trace surfaces cannot be reconciled.""" pass class ReservationState(Enum): RESERVED = "reserved" QUARANTINED = "quarantined" SETTLED = "settled" RELEASED = "released" BILLED_UNACKNOWLEDGED = "billed_unacknowledged" @dataclass class Reservation: authorizing_instance: str logical_call_id: str attempt_epoch: int tokens: int state: ReservationState = ReservationState.RESERVED settled_epoch: Optional[int] = None @dataclass class TraceSpan: emitting_instance: str logical_call_id: str attempt_epoch: int tokens: int status: str # "ok" | "timeout" | "rejected" @dataclass class Ledger: reservations: Dict[str, Reservation] = field(default_factory=dict) def key(self, r: Reservation) -> str: return f"{r.authorizing_instance}:{r.logical_call_id}:{r.attempt_epoch}" def reserve(self, r: Reservation) -> None: self.reservations[self.key(r)] = r def committed_tokens(self, instance: str) -> int: # Enforce against RESERVED + QUARANTINED, never SETTLED-only. return sum( r.tokens for r in self.reservations.values() if r.authorizing_instance == instance and r.state in (ReservationState.RESERVED, ReservationState.QUARANTINED) ) def on_dispatch_timeout(ledger: Ledger, r: Reservation) -> None: # Do NOT release on timeout: backend may have billed. Quarantine. k = ledger.key(r) if k not in ledger.reservations: raise AttributionInvariantError(f"unknown reservation {k}") ledger.reservations[k].state = ReservationState.QUARANTINED def settle(ledger: Ledger, r: Reservation, epoch: int) -> None: k = ledger.key(r) if k not in ledger.reservations: raise AttributionInvariantError(f"settle on unknown reservation {k}") # Exactly one epoch may settle per logical call. for other in ledger.reservations.values(): if (other.authorizing_instance == r.authorizing_instance and other.logical_call_id == r.logical_call_id and other.state == ReservationState.SETTLED and other.settled_epoch != epoch): raise AttributionInvariantError( f"double-settle on {r.logical_call_id}: " f"epoch {other.settled_epoch} already settled" ) ledger.reservations[k].state = ReservationState.SETTLED ledger.reservations[k].settled_epoch = epoch def reconcile(ledger: Ledger, spans: list[TraceSpan], settle_window_elapsed: bool) -> int: """Return count of billed_unacknowledged orphans attributed.""" if not settle_window_elapsed: raise AttributionInvariantError("reconcile before settle window elapsed") orphans = 0 span_index = {(s.logical_call_id, s.attempt_epoch): s for s in spans} for k, r in ledger.reservations.items(): if r.state != ReservationState.QUARANTINED: continue span = span_index.get((r.logical_call_id, r.attempt_epoch)) if span is None or span.status == "ok": # Ok-span on a quarantined epoch means settlement was lost. raise AttributionInvariantError( f"quarantined reservation {k} has ok-span or no span; " f"settlement path broken" ) if span.status == "timeout": r.state = ReservationState.BILLED_UNACKNOWLEDGED orphans += 1 else: r.state = ReservationState.RELEASED return orphans ```