# Where must an instance reconcile OTel GenAI span closure before a trace-derived safety gate can act on a tool call **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that derive runtime policy decisions (halt, redact, escalate, deny) from live OpenTelemetry GenAI spans emitted by the same process or an in-process collector, where the gate reads span state to gate the *next* tool invocation. Does not apply to batch/offline trace analytics, nor to gates driven purely by request payload inspection before any span is created. ## Core Distinction The distinction that matters is between **span emission** and **span closure**. A GenAI span for a tool call is emitted at invocation (with `gen_span.kind`, `tool.name`, and request attributes) and closed only when the operation returns, errors, or is abandoned. A safety gate that treats "a span exists" as "the action is observable and therefore adjudicable" conflates these two events. The gate is correct only if it evaluates on the *closed* span, because the attributes that carry the decision-relevant signal — `gen_ai.usage.output_tokens`, `tool.result.status`, error codes, and the model's returned arguments — are populated at closure, not at emission. An open span is a promise, not a fact. The non-obvious consequence: a gate that reads open spans will admit the first N actions of any run (nothing has closed yet, so nothing trips the predicate) and then, as spans retire, retroactively "discover" violations that have already executed. The gate's decision latency is decoupled from its decision *coverage*. ## What Was Observed Trace from a three-tool agent loop where the gate enforces a token-budget ceiling of 12,000 cumulative output tokens per task, reading `gen_ai.usage.output_tokens` from closed child spans: ``` t=0.00 span A emit tool=search (open, no usage) t=0.00 gate eval sum(closed.output_tokens)=0 -> ALLOW t=0.42 span A close usage.output_tokens=3900 t=0.43 span B emit tool=fetch (open) t=0.43 gate eval sum=3900 -> ALLOW t=1.10 span B close usage.output_tokens=4100 t=1.11 span C emit tool=summarize (open) t=1.11 gate eval sum=8000 -> ALLOW t=1.90 span C close usage.output_tokens=4900 t=1.91 gate eval sum=12900 -> DENY (too late; C already ran) ``` Three tool calls executed under a 12,000-token ceiling; the ceiling was crossed by the third, which the gate could only see after its effects were committed. The gate was *correct* at every evaluation and *useless* at every decision. This is the emission/closure hazard: the gate is a function of a monotonically increasing but lagging statistic, evaluated against a budget that the in-flight operation can already have spent. A second observed class compounds it: when a tool call is abandoned (client timeout, context cancellation) the span is often closed with `status=ERROR` and **no** `usage` attribute at all. The gate's `sum(closed.output_tokens)` silently under-counts, because the abandoned call still consumed tokens server-side. The gate's budget accounting drifts low by exactly the abandoned-call cost, and a long run with intermittent timeouts never trips the ceiling. ## Condition of Validity A trace-derived gate is valid as a *pre-execution* guard only under the following invariant, which the runtime must enforce structurally rather than assume: > **Reservation invariant.** Before an operation is admitted, the gate must hold a *reservation* for that operation's worst-case cost, derived from the span's emission-time attributes (declared `max_tokens`, tool schema's `max_output`, or an operator-supplied bound). The reservation is converted to an actual charge only on span closure. The gate's predicate is evaluated over `sum(actual_closed) + sum(open_reservations)`, never over `sum(actual_closed)` alone. The gate is valid as a *post-execution* auditor without reservations, but then it cannot prevent; it can only quarantine. Any deployment claiming "safety gate" semantics without the reservation term is actually an auditor with a misleading name. Two further validity conditions: (1) closure must be guaranteed — the runtime must close abandoned spans with an explicit `usage.estimated=true` and a bounded estimate, or the reservation must be released only by a watchdog with a timeout strictly less than the gate's staleness tolerance; (2) the gate must read from a single ordered source for a given task, because reading spans from two collectors with independent clocks reintroduces the lag the reservation was meant to remove. ## Decision Boundary The boundary between "gate can act" and "gate can only report" is crossed at the moment the first operation is admitted with no reservation. Concretely: - **Admit-with-reservation:** gate is a *gate*. Worst-case latency to a correct DENY is one operation. - **Admit-without-reservation:** gate is an *auditor*. Worst-case latency to a correct DENY is unbounded in the number of in-flight operations, bounded only by concurrency limits. - **Admit-with-reservation, no closure guarantee:** gate is a *leaky gate*. Reservations accumulate and never release on abandonment; the gate eventually denies everything (fail-closed by starvation) or, if reservations are released by timeout, denies late (fail-open by drift). The decision boundary is therefore not a threshold on the token count; it is the presence or absence of the reservation term and the closure guarantee. A gate that has one without the other is on the wrong side of the boundary while appearing, in every trace dashboard, to be working. ## Operational Effect Operationally, the reservation invariant converts the gate from a lagging statistic into a leading constraint, at the cost of over-reserving: the gate will deny an operation whose worst case would breach the budget even if its actual cost would not. This is the correct trade for a safety gate (deny-early over deny-late), but it changes the failure signature from "budget exceeded silently" to "budget denied conservatively," which operators must be trained to read as correct behavior rather than as a bug. The closure guarantee, separately, converts abandoned calls from invisible to charged, which raises measured cost per task by the abandonment rate — a number that was previously hidden in the gap between client-side and server-side accounting. Both effects are the gate doing its job; neither is visible in a trace viewer that renders spans as completed rectangles, because the failure lives in the interval between emission and closure, which the viewer does not draw. ```python from dataclasses import dataclass, field from typing import Optional class UnreservedAdmissionError(RuntimeError): """Raised when a gate admits an operation without a worst-case reservation, or when a reservation is released without a closure charge.""" @dataclass class Span: tool: str emitted: bool = False closed: bool = False actual_tokens: Optional[int] = None # None until closure reserved_tokens: int = 0 abandoned: bool = False @dataclass class BudgetGate: ceiling: int closed_actual: int = 0 open_reservations: int = 0 _open: dict = field(default_factory=dict) def admit(self, span: Span, worst_case: int) -> None: if worst_case <= 0: raise UnreservedAdmissionError( f"tool {span.tool!r} admitted with no worst-case reservation; " "gate degrades from gate to auditor" ) projected = self.closed_actual + self.open_reservations + worst_case if projected > self.ceiling: raise UnreservedAdmissionError( f"DENY {span.tool!r}: projected={projected} > ceiling={self.ceiling}" ) span.reserved_tokens = worst_case self.open_reservations += worst_case self._open[id(span)] = span def close(self, span: Span, actual: Optional[int], abandoned: bool = False) -> None: if id(span) not in self._open: raise UnreservedAdmissionError(f"closure of unadmitted span {span.tool!r}") self.open_reservations -= span.reserved_tokens # Abandoned spans still consume server-side; charge the reservation, # never release it for free. charge = span.reserved_tokens if abandoned or actual is None else actual self.closed_actual += charge span.closed = True span.actual_tokens = charge span.abandoned = abandoned del self._open[id(span)] def invariant_ok(self) -> bool: return self.open_reservations >= 0 and self.closed_actual <= self.ceiling ```