What happens when an instance emits GenAI span attributes for a tool call whose response is truncated by the model's own token budget: the `gen_ai.completion.0.finish_reason` / `tool_calls` divergence and its effect on multi-turn replay

**Date of Record:** 2026 December 1

**Scope:** Applies to any agent runtime instrumented with OpenTelemetry GenAI semantic conventions (v1.27+) where a single logical tool call is traced as one span and the model may terminate generation with `finish_reason = "length"` mid-`tool_calls`. Does not apply to streaming-only spans that emit per-chunk events without a terminal `finish_reason`, nor to non-GenAI spans.

Core Distinction

The GenAI semantic conventions model a model invocation as a span with `gen_ai.operation.name = "chat"` and a `gen_ai.completion.N` indexed set of choices. Each choice carries `finish_reason` and, when the model emits a tool call, `message.tool_calls` (or the newer `gen_ai.tool.call.id` / `gen_ai.tool.name` / `gen_ai.tool.call.arguments` attributes on a child span). The convention assumes these two facts are *causally consistent*: if `finish_reason` is `tool_calls`, the arguments JSON is complete and parseable; if `finish_reason` is `length`, no tool call was emitted. Reality diverges. A model can emit `finish_reason = "length"` *after* having already streamed a partial `tool_calls` array whose `arguments` string is a syntactically invalid JSON prefix. The span records both. Downstream replay, audit, and distillation pipelines that trust the convention's implied invariant (finish_reason ⟹ tool_calls shape) silently ingest a call that was never valid.

This is not a generic "spans can be malformed" observation. It is a specific violation of the *implicit* contract that the semantic convention encodes in its attribute set but does not enforce: `finish_reason` is a terminal-state discriminator, and `tool_calls` is a payload whose validity is supposed to be entailed by that discriminator.

What Was Observed

Trace from a multi-turn agent (turn 7 of a 12-turn task), model `claude-sonnet`, single `chat` span:

gen_ai.operation.name = "chat"
gen_ai.request.model = "claude-sonnet"
gen_ai.usage.input_tokens = 187,412
gen_ai.usage.output_tokens = 4096
gen_ai.response.finish_reasons = ["length"]
gen_ai.completion.0.finish_reason = "length"
gen_ai.completion.0.message.role = "assistant"
gen_ai.completion.0.message.tool_calls.0.id = "toolu_01X..."
gen_ai.completion.0.message.tool_calls.0.type = "function"
gen_ai.completion.0.message.tool_calls.0.function.name = "write_file"
gen_ai.completion.0.message.tool_calls.0.function.arguments = '{"path": "/repo/src/agent/loop.py", "content": "import asyncio\n\nasync def run(sta'

The `arguments` string is 4096-token-truncated mid-string-literal. It is not valid JSON. The agent runtime's parser raised `json.JSONDecodeError`, the runtime treated the turn as a hard failure, and — critically — the *span was already exported* as a successful `chat` operation with a `tool_calls` child. The runtime's failure was recorded in a *separate* span (`agent.turn.execute`, status `ERROR`) that did not reference the malformed tool call by ID. On replay, the distillation pipeline that extracts `(tool_name, arguments) → result` tuples from the trace picked up the truncated call, attempted to re-execute `write_file` with a repaired-by-truncation content string, and wrote a *partial* file to the sandbox — a file whose content was 60% of the intended module but syntactically valid Python. The agent's next turn read that file back, reasoned over it, and concluded the task was complete.

The failure is a *trace-level* invariant violation, not an execution-time one. The execution was correctly rejected. The trace was not.

Condition of Validity

The convention's implied invariant holds only under three conditions, none of which the OTel GenAI spec enforces:

  1. **Terminal-state monotonicity.** `finish_reason` must be set exactly once per choice, at the terminal event, and must be the *last* attribute written. In streaming implementations the finish reason often arrives in a separate SSE frame *after* the tool-call deltas; if the exporter flushes on the tool-call frame and the finish-reason frame races, the span can be exported with `finish_reason` absent or defaulted to `"stop"` while `tool_calls` is present and truncated. The observed trace had `finish_reason = "length"`, which is the *correct* value — the failure is that the downstream consumer never checked it.
  1. **Arguments completeness entailment.** `tool_calls.N.function.arguments` is specified as a JSON string, but the spec does not state that the string is complete iff `finish_reason ∈ {"tool_calls", "stop"}`. A conformant exporter may emit a partial string. There is no `gen_ai.tool.call.truncated` boolean, no `gen_ai.tool.call.complete` attribute, no sentinel. The consumer has no signal except re-parsing.
  1. **Cross-span referential integrity.** The `chat` span and the `agent.turn.execute` span are siblings, not parent-child in the observed trace (the runtime used a manual span, not the GenAI auto-instrumentation, for the turn wrapper). The malformed tool call's `id` (`toolu_01X...`) appears in the `chat` span but is *not* referenced by the error span. A trace consumer correlating by `tool_call.id` finds no error; a consumer correlating by `trace_id` finds the error but must know to join on the turn boundary. Neither join is specified.

The invariant is valid only when the trace consumer independently re-parses `arguments` and treats parse failure as a hard exclusion — which is exactly the step the distillation pipeline skipped because the convention *implied* it wasn't necessary.

Decision Boundary

The boundary is between two trace-consumer classes:

The boundary is crossed whenever a consumer uses `presence of tool_calls` as the predicate for "a tool was called" without gating on `finish_reason ∈ {"tool_calls", "stop"}` **and** re-parsing `arguments`. The observed failure crossed it in the replay direction: the pipeline used presence-as-predicate, repaired the JSON by truncation (a lossy, silent operation), and re-executed.

The correct guardrail is a *trace-level admission check*: before any consumer acts on a `tool_calls` entry, it asserts `finish_reason` is a member of the valid-terminal set and that `arguments` parses. Failure of either is a `TruncatedToolCallError`, not a warning, and the span is quarantined from replay.

Operational Effect

The operational effect is *silent partial execution under a green trace*. Because the `chat` span carried no error status (the model call succeeded; the model simply ran out of budget), dashboards showed turn 7 as a successful 4096-token completion. The runtime's `agent.turn.execute` error span was emitted but not linked, so error-rate SLOs computed over `gen_ai.operation.name = "chat"` spans did not register it. The distillation pipeline's re-execution wrote a partial file, and the agent's self-verification (reading the file back) passed because the partial file was valid Python. The task was marked complete at turn 12 with a 60%-complete module.

The invariant to enforce, restated as a guardrail: **`finish_reason` is a validity gate for `tool_calls`, not merely a label.** Any consumer that treats a `tool_calls` entry as an executable unit must (a) require `finish_reason ∈ {"tool_calls", "stop"}`, (b) re-parse `arguments` and reject on failure, and (c) link the `chat` span to the turn-execution span by `tool_call.id` so that execution-time rejection is visible to trace-level consumers. Without (a)–(c), the convention's attribute set is a *record of what the model emitted*, not a *record of what the agent did* — and replaying the former as the latter is how a truncated tool call becomes a committed side effect.

import json
from dataclasses import dataclass
from typing import Any, Mapping

VALID_TERMINAL_FINISH_REASONS = frozenset({"tool_calls", "stop"})


class TruncatedToolCallError(RuntimeError):
    """Raised when a GenAI span's tool_calls entry is not a complete, executable call.

    Triggered when finish_reason is a non-terminal discriminator (e.g. "length")
    or when the arguments JSON string fails to parse. Either condition means the
    tool call was emitted but never validly completed, and must be quarantined
    from replay / distillation / re-execution pipelines.
    """


@dataclass(frozen=True)
class ToolCall:
    id: str
    name: str
    arguments: str


def extract_executable_tool_calls(span_attributes: Mapping[str, Any]) -> list[ToolCall]:
    """Admission check for replay consumers.

    Enforces the invariant: finish_reason gates tool_calls validity.
    Raises TruncatedToolCallError on any violation; never repairs, never
    silently drops, never returns a partial call.
    """
    finish_reason = span_attributes.get("gen_ai.completion.0.finish_reason")
    if finish_reason not in VALID_TERMINAL_FINISH_REASONS:
        if "gen_ai.completion.0.message.tool_calls.0.id" in span_attributes:
            raise TruncatedToolCallError(
                f"tool_calls present under non-terminal finish_reason="
                f"{finish_reason!r}; span records a truncated call, not an "
                f"executable one"
            )
        return []

    calls: list[ToolCall] = []
    index = 0
    while True:
        prefix = f"gen_ai.completion.0.message.tool_calls.{index}"
        call_id = span_attributes.get(f"{prefix}.id")
        if call_id is None:
            break
        name = span_attributes.get(f"{prefix}.function.name")
        raw_args = span_attributes.get(f"{prefix}.function.arguments", "")
        try:
            json.loads(raw_args)
        except json.JSONDecodeError as exc:
            raise TruncatedToolCallError(
                f"tool call {call_id!r} ({name!r}) has unparseable arguments "
                f"despite finish_reason={finish_reason!r}; arguments prefix="
                f"{raw_args[:64]!r}..."
            ) from exc
        calls.append(ToolCall(id=call_id, name=name, arguments=raw_args))
        index += 1
    return calls