# What structural signals indicate span-attribute truncation is corrupting token accounting in OpenTelemetry GenAI agent traces **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans per the GenAI semantic conventions (`gen_ai.*` attributes) where tool-call arguments/results and token usage are recorded as span attributes. Does not address metrics-only pipelines, log-based telemetry, or non-conformant custom attribute schemes. ## Core Distinction The GenAI semantic conventions treat token usage (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) and tool-call payloads (`gen_ai.tool.call.arguments`, `gen_ai.tool.call.result`) as *span attributes*—flat key/value strings attached to the span at emission time. The distinction that matters operationally is between **truncation as a display concern** and **truncation as a propagation concern**. Most teams assume that trimming a large tool result to fit an attribute size limit only degrades the human-readable trace. In fact, the truncation is applied *before* the span is finalized, and the token counters on the same span are computed from the *post-truncation* payload. The trace looks compliant, the counters look plausible, and the accounting silently under-reports the true context cost of the step. This is not a rendering bug; it is a state-transfer loss inside the telemetry plane that propagates into every downstream aggregation. The failure is non-obvious because OTel itself does not truncate. The loss happens in the exporter/SDK attribute-serialization path or in the agent framework's span wrapper, and it is invisible in the trace UI because the truncated value is a valid string. ## What Was Observed A multi-step agent performing retrieval-augmented tool calls emitted spans where `gen_ai.usage.input_tokens` reported ~1,800 tokens per turn, but the orchestrator's own context-window meter showed ~7,400 tokens on the same turns. The ratio was stable at roughly 0.24 across hundreds of spans—too consistent to be noise. Tracing the emission path revealed the mechanism: 1. The tool returned a 42 KB JSON document. The agent framework attached it as `gen_ai.tool.call.result`. 2. The OTel SDK's attribute serializer enforced a per-attribute byte cap (backend-imposed, commonly 8–64 KB depending on collector config). The serializer *clipped* the string to the cap but did **not** raise an error or set a truncation flag. 3. The agent's token-counting wrapper computed `input_tokens` by tokenizing the *attribute value it had just written into the span buffer*—i.e., the clipped string—rather than the string actually passed to the model. 4. The span finalized and exported. `gen_ai.tool.call.result` was a valid, well-formed (but shorter) JSON fragment; `gen_ai.usage.input_tokens` was a valid integer. No span status was set to `ERROR`. Structural signals that flagged the corruption, in order of reliability: - **Token/byte ratio discontinuity.** Across sibling tool-call spans, the `input_tokens`-to-`gen_ai.tool.call.result` byte-length ratio should be roughly constant for a fixed tokenizer. A sudden step-change in that ratio at a specific byte length (the cap) is the signature of clipping. - **Truncated JSON is still parseable-looking but semantically short.** The clipped result ended mid-object; a schema validator against the tool's declared output schema failed with "missing required property," which is the tell that the attribute is not the payload the model saw. - **Absent `gen_ai.usage` reconciliation.** The sum of per-span `input_tokens` did not reconcile with the model provider's billing counter for the same request window. The gap equals the clipped bytes' token equivalent. - **No `otel.status_code` escalation.** Because the clip is silent, the span is marked `UNSET`/`OK`, so error-rate dashboards never fired. ## Condition of Validity The invariant "span token counters reflect the model's true context cost" holds **only if** the attribute value used to compute the counter is byte-identical to the payload submitted to the model *and* the attribute survived serialization without clipping. It is violated whenever: - Any per-attribute byte cap exists in the SDK, collector, or backend, **and** - The counter is derived from the attribute buffer (common in frameworks that count tokens inside the span-emission function), **and** - The cap is applied before the counter is computed. The invariant is preserved (and this failure cannot occur) when the counter is computed from the model request object *before* span construction, or when clipping is accompanied by an explicit `gen_ai.tool.call.result.truncated=true` marker and a recomputed counter. The boundary is therefore a strict ordering condition: **count-before-clip, never clip-before-count.** ## Decision Boundary The operational decision is whether to treat a clipped tool-call attribute as a *telemetry cosmetic* or as a *correctness fault requiring span invalidation*. The boundary condition: - If `gen_ai.tool.call.result` byte length equals the configured cap **and** the value fails the tool's declared output schema **and** the span's `input_tokens` does not reconcile with the provider counter within tolerance → the span is **invalid for accounting**; it must be dropped from token-cost aggregation and flagged, not silently summed. - If the same conditions hold but reconciliation passes → the clip occurred after counting; the span is valid for accounting and only the payload view is degraded. The failure mode is choosing the first branch's remedy (drop) for the second branch's case (over-counting loss) or vice versa. The reconciliation check against the provider counter is the discriminator; it must run before any aggregation consumes the span. ## Operational Effect When the boundary is mis-classified, three downstream effects compound: 1. **Cost attribution under-reports context growth.** Because clipped spans under-count, the agent's context-window saturation is invisible in telemetry until the model provider returns a hard context-limit error—the exact failure the trace was supposed to predict. 2. **Distillation loss across steps.** Episodic trace data is the substrate for later semantic summarization; clipped tool results mean the summarized "what the agent saw" diverges from what it actually saw, and the divergence is unrecoverable post-hoc. 3. **Silent SLO drift.** Error-rate and latency SLOs stay green while the token-budget SLO is computed from corrupted inputs, so token exhaustion appears as a sudden cliff rather than a trend. The guardrail is a span-finalization validator that enforces count-before-clip ordering, emits an explicit truncation marker, and refuses to let a non-reconciling span enter the accounting pipeline. ```python import json from dataclasses import dataclass class TelemetryAccountingFault(RuntimeError): """Raised when a GenAI span's token counters cannot be trusted for accounting.""" pass @dataclass class GenAISpan: name: str attributes: dict input_tokens: int output_tokens: int status_code: str = "UNSET" def validate_span_for_accounting( span: GenAISpan, tool_output_schema: dict, provider_input_tokens: int, attribute_byte_cap: int, reconciliation_tolerance: float = 0.05, ) -> str: """ Classify a GenAI tool-call span as valid or invalid for token accounting. Returns 'valid' or raises TelemetryAccountingFault with the reason. """ result = span.attributes.get("gen_ai.tool.call.result") if result is None: return "valid" # no tool payload on this span; nothing to clip result_bytes = len(result.encode("utf-8")) at_cap = result_bytes >= attribute_byte_cap if not at_cap: return "valid" # At the cap: determine whether clipping happened before or after counting. schema_ok = True try: json.loads(result) except json.JSONDecodeError: schema_ok = False if schema_ok: required = tool_output_schema.get("required", []) parsed = json.loads(result) schema_ok = all(k in parsed for k in required) if schema_ok: # Payload survived intact enough to satisfy schema: clip was cosmetic. return "valid" # Payload is clipped. Use provider counter to decide the branch. if span.input_tokens == 0: raise TelemetryAccountingFault( f"span {span.name}: clipped tool result with zero input_tokens; " f"counter was never computed from the real payload" ) drift = abs(span.input_tokens - provider_input_tokens) / max(provider_input_tokens, 1) if drift > reconciliation_tolerance: raise TelemetryAccountingFault( f"span {span.name}: clipped result at {result_bytes} bytes (cap " f"{attribute_byte_cap}); input_tokens={span.input_tokens} vs provider=" f"{provider_input_tokens} (drift {drift:.1%}). Span invalid for " f"accounting; clip-before-count ordering detected." ) # Reconciles despite clipping: clip happened after counting; mark truncated # but keep the span in the accounting pipeline. span.attributes["gen_ai.tool.call.result.truncated"] = True return "valid" def finalize_batch(spans, schema, provider_totals, cap): accepted, rejected = [], [] for sp in spans: try: validate_span_for_accounting( sp, schema, provider_totals[sp.name], cap ) accepted.append(sp) except TelemetryAccountingFault as e: rejected.append((sp.name, str(e))) if not accepted and spans: raise TelemetryAccountingFault( f"all {len(spans)} spans failed accounting validation: {rejected}" ) return accepted, rejected ```