# Stop LLM JSON Truncation Retry Loops: max_tokens & Reasoning Traps

> Canonical URL: https://stackquota.com/guides/llm-structured-json-truncation-retry-cost-loop/
> Checked: 2026-12-04 · Published: 2026-12-04

Fix finish_reason: length, stop_reason: max_tokens, and MAX_TOKENS JSON parse retry loops when reasoning tokens starve structured output budgets.

The most expensive silent bug in production LLM engineering returns `HTTP 200 OK` every single time it fails. You enable `response_format: { type: "json_schema", strict: true }`, wrap `JSON.parse()` and Zod validation inside a 3-attempt retry helper, and assume schema syntax errors are extinct. Two weeks later, your billing alert fires: output token spend jumped 400%, P99 latency hit 38 seconds, and dead-letter queues are full of `SyntaxError: Unterminated string in JSON at position 6142`.

What happened is a **structured JSON truncation retry loop**, where internal reasoning tokens or dense array extractions hit your `max_tokens` ceiling mid-stream, and your validation loop blindly re-runs the exact same doomed request at maximum output token prices.

## Why do strict structured outputs still return broken, unparseable JSON?

**Quick answer:** Grammar-constrained decoding (`strict: true`, `responseSchema`, or forced tool input) guarantees token-level compliance only while tokens are being sampled, not clean closure at an arbitrary token limit. When generation hits `max_completion_tokens` or `max_tokens`, the provider severs the stream mid-token with `HTTP 200 OK` and sets `finish_reason: "length"`.

Because the HTTP status code is `200`, generic HTTP clients treat truncated responses as successful network calls and hand the raw string directly to `JSON.parse()`. Even worse, on reasoning-capable models, `max_completion_tokens` governs **internal reasoning tokens plus visible JSON tokens combined**. If internal chain-of-thought consumes the entire budget before emitting `{`, `message.content` arrives completely empty (`""`) while billing you for thousands of invisible output tokens.

Compare the exact truncation telemetry payloads across OpenAI, Anthropic, and Google Gemini:

```json
{
  "openai_reasoning_starvation": {
    "choices": [
      {
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "",
          "refusal": null
        },
        "finish_reason": "length"
      }
    ],
    "usage": {
      "prompt_tokens": 4120,
      "completion_tokens": 2048,
      "total_tokens": 6168,
      "completion_tokens_details": {
        "reasoning_tokens": 2048,
        "accepted_prediction_tokens": 0,
        "rejected_prediction_tokens": 0
      }
    }
  },
  "anthropic_mid_json_cut": {
    "stop_reason": "max_tokens",
    "usage": {
      "input_tokens": 4120,
      "output_tokens": 4096
    }
  },
  "gemini_thought_exhaustion": {
    "candidates": [
      {
        "finishReason": "MAX_TOKENS"
      }
    ],
    "usageMetadata": {
      "promptTokenCount": 4120,
      "candidatesTokenCount": 312,
      "thoughtsTokenCount": 3784,
      "totalTokenCount": 8216
    }
  }
}
```

In `openai_reasoning_starvation`, the caller set `max_completion_tokens: 2048` expecting a `400`-token JSON object. The model (`o4-mini` or `gpt-5` with elevated reasoning effort) spent all `2,048` tokens thinking internally, emitted `0` visible characters, threw `SyntaxError: Unexpected end of JSON input` in `JSON.parse("")`, and triggered three immediate retries, burning `8,192` billed output tokens to return an error to the user.

## How do OpenAI, Anthropic, and Gemini budget reasoning vs visible JSON tokens?

**Quick answer:** All three providers bill internal reasoning tokens at full output token prices and deduct them from your top-level output limit (`max_completion_tokens`, `max_tokens`, or `maxOutputTokens`), requiring explicit reasoning caps (`reasoning_effort`, `thinking.budget_tokens`, or `thinkingConfig.thinkingBudget`) to reserve guaranteed headroom for JSON serialization.

When migrating extraction pipelines from non-reasoning models like `gpt-4.1` (`$2.00` input / `$8.00` output) to hybrid reasoning models like `gpt-5`, `o4-mini`, `claude-sonnet-5.5`, or `gemini-2.5-flash`, copying legacy `max_tokens: 1024` settings is the number-one trigger for overnight truncation spikes.

| Model Family (Dec 2026) | Input / Output per 1M | Truncation Signal | Hidden Reasoning Usage Field | How to Reserve Visible JSON Headroom |
| :--- | :---: | :--- | :--- | :--- |
| **OpenAI `gpt-5` / `gpt-5-mini`** | `$1.25 / $10.00` · `$0.25 / $2.00` | `finish_reason === "length"` | `usage.completion_tokens_details.reasoning_tokens` | Set `reasoning_effort: "low"` (or `"minimal"`) for extraction and size `max_completion_tokens >= reasoning + 2x schema` |
| **OpenAI `o4-mini` (Reasoning)** | `$1.10 / $4.40` | `finish_reason === "length"` | `usage.completion_tokens_details.reasoning_tokens` | Never pass `< 4096` `max_completion_tokens`; set `reasoning_effort: "low"` for deterministic schema mapping |
| **OpenAI `gpt-4.1`** | `$2.00 / $8.00` | `finish_reason === "length"` | `0` (non-reasoning architecture) | `100%` of `max_completion_tokens` is available for visible JSON tokens |
| **Claude Sonnet 5.5 / Opus 5.5** | `$2.00 / $10.00` · `$5.00 / $25.00` | `stop_reason === "max_tokens"` | Billed inside `usage.output_tokens` | Omit `thinking` for pure extraction, or enforce `max_tokens >= thinking.budget_tokens + 2048` |
| **Claude Haiku 5.5** (`<=100K`) | `$0.10 / $0.50` | `stop_reason === "max_tokens"` | Billed inside `usage.output_tokens` | Disable extended thinking on high-speed JSON routing; cap array cardinality per batch |
| **Gemini 3.1 Pro / 2.5 Flash** | `$2.00 / $12.00` · `$0.30 / $2.50` | `finishReason === "MAX_TOKENS"` | `usageMetadata.thoughtsTokenCount` | Set explicit `thinkingConfig: { thinkingBudget: 512 }` (or `0` on Flash) alongside `maxOutputTokens` |

Notice why blindly setting `max_tokens: 32768` everywhere is **not** a safe fix either. First, as covered in our [HTTP 429 rate-limit guide](/guides/fix-429-rate-limit-tpm-rpm-openai-anthropic-gemini/), Anthropic `OTPM` and OpenAI admission controllers reserve `max_tokens` upfront, meaning `max_tokens: 32768` slashes your allowed concurrent in-flight requests by 8x to 16x. Second, if a schema contains an unconstrained string field (`"detailed_notes": { "type": "string" }`) and the sampler enters a degenerate whitespace or markdown repetition loop, a `32,768` cap lets a single wedged call burn `$0.33` on `gpt-5` or `$0.82` on `claude-opus-5.5` while holding open serverless sockets (risking [Cloudflare Workers Error 1102 memory exhaustion](/guides/cloudflare-workers-error-1102-cpu-memory-limit-fix/) when buffering multi-megabyte streams).

## What is the exact invoice impact of a 5% JSON truncation retry rate?

**Quick answer:** Because output tokens cost **5x to 8x more than input tokens**, and every truncated attempt consumes 100% of its `max_tokens` ceiling, a 5% truncation rate wrapped in a 3-retry loop can more than **double** total monthly output spend while still returning `500` errors to callers.

Unlike normal API calls that average `350` output tokens, a truncated call always bills the full ceiling (`4,096` or `8,192` tokens). When a naive schema validator catches `SyntaxError` and retries 3 more times with the exact same `prompt` + `max_tokens: 4096` configuration, a single failing document consumes `4 * 4,096 = 16,384` output tokens (`46.8x` the output cost of a healthy call!).

Let's run the December 2026 numbers for a document-extraction service processing **2,000,000 documents per month** (`3,000` input tokens each, `400` average output tokens on the 95% healthy path, and `max_tokens: 4096` with up to 3 retries on the 5% (`100,000` docs) that exceed `4,096` combined reasoning + JSON tokens):

- **Healthy 95% traffic (`1.9M` calls)**:
  - Input (`5,700M` tokens, assuming 50% cached prefix): on `gpt-5` (`$1.25` base / `$0.125` cached) = **$3,918.75**; on `claude-sonnet-5.5` (`$2.00` base / `$0.20` cached read) = **$6,270.00**.
  - Output (`760M` tokens): on `gpt-5` (`$10.00/1M`) = **$7,600.00**; on `claude-sonnet-5.5` (`$10.00/1M`) = **$7,600.00**; on `claude-opus-5.5` (`$25.00/1M`) = **$19,000.00**.
- **Wasted 5% truncation retry loop (`100,000` docs × 4 attempts = `400,000` failed calls at `4,096` output tokens = `1,638.4M` wasted output tokens + `1,200M` extra input tokens)**:
  - **On `gpt-5`**: `$16,384.00` wasted output + ~$825 input = **$17,209/mo burned for zero valid outputs** (inflating your `$11,518` healthy bill by **+149%**!).
  - **On `claude-sonnet-5.5`**: `$16,384.00` wasted output + ~$1,320 input = **$17,704/mo wasted** (+128% bill spike).
  - **On `claude-opus-5.5`**: `1,638.4M * $25.00/1M` = **$40,960.00/mo wasted** in output tokens alone!
  - **On `gemini-3.1-pro` (`<=200K` at `$12.00/1M` output)**: `1,638.4M * $12.00/1M` = **$19,660.80/mo wasted**.

Even on budget reasoning tier `o4-mini` (`$4.40/1M` output), burning `1,638.4M` invisible reasoning + truncated tokens wastes **$7,208.96/mo**. Test how output-heavy retry multipliers distort your own unit economics in our [LLM API Pricing Calculator](/calculators/llm-api-pricing/).

## How do you write a Truncation-Safe structured output guard in TypeScript?

**Quick answer:** Inspect `finish_reason` / `stop_reason` / `finishReason` **before** invoking `JSON.parse()`, abort immediately on safety refusals, size `max_completion_tokens` as explicit `reasoningBudget + schemaTokenBudget`, and on a `length` cut perform at most **one** escalated retry that doubles visible headroom while dropping `reasoning_effort` to `"low"`.

Never feed raw response text into `JSON.parse()` without checking why generation stopped. If `finish_reason === "length"`, re-sending the identical token cap has near-zero probability of succeeding on deterministic (`temperature: 0`) extraction, you **must** change either the token budget, the reasoning effort, or the input chunk size before retrying once. Also, keep your JSON schema keys canonically sorted so retries hit your warm prefix cache (see [fixing LLM prompt caching misses](/guides/prompt-caching-miss-bugs-openai-anthropic-gemini/)).

Here is a complete, provider-agnostic TypeScript guard for structured extraction:

```typescript
export type StopCategory = "completed" | "truncated" | "refusal" | "filtered";

export interface NormalizedRawResponse {
  rawJsonText: string;
  stopCategory: StopCategory;
  refusalReason?: string;
  reasoningTokens: number;
  visibleTokens: number;
}

export class StructuredOutputBudgetError extends Error {
  constructor(msg: string, public readonly reasoningTokens: number, public readonly visibleTokens: number) {
    super(msg);
    this.name = "StructuredOutputBudgetError";
  }
}

export function classifyOpenAiCompletion(resp: any): NormalizedRawResponse {
  const choice = resp?.choices?.[0];
  const reason = choice?.finish_reason;
  const refusal = choice?.message?.refusal;
  const reasoning = resp?.usage?.completion_tokens_details?.reasoning_tokens ?? 0;
  const visible = Math.max(0, (resp?.usage?.completion_tokens ?? 0) - reasoning);

  if (refusal || reason === "refusal") {
    return { rawJsonText: "", stopCategory: "refusal", refusalReason: String(refusal ?? "refusal"), reasoningTokens: reasoning, visibleTokens: visible };
  }
  if (reason === "content_filter") {
    return { rawJsonText: "", stopCategory: "filtered", reasoningTokens: reasoning, visibleTokens: visible };
  }
  return {
    rawJsonText: choice?.message?.content ?? "",
    stopCategory: reason === "length" ? "truncated" : "completed",
    reasoningTokens: reasoning,
    visibleTokens: visible,
  };
}

export interface BoundedSchemaOptions<T> {
  initialSchemaTokens: number;
  initialReasoningBudget: number;
  hardCeilingTokens: number;
  parseAndValidate: (parsed: unknown) => T;
  executeCall: (p: { maxCompletionTokens: number; reasoningEffort: "low" | "medium" }) => Promise<NormalizedRawResponse>;
}

export async function runBoundedStructuredExtraction<T>(opts: BoundedSchemaOptions<T>) {
  let schemaBudget = opts.initialSchemaTokens;
  let effort: "low" | "medium" = opts.initialReasoningBudget > 512 ? "medium" : "low";

  for (let attempt = 0; attempt < 2; attempt++) {
    const maxCompletionTokens = Math.min(
      opts.hardCeilingTokens,
      schemaBudget + (effort === "low" ? 384 : opts.initialReasoningBudget)
    );
    const out = await opts.executeCall({ maxCompletionTokens, reasoningEffort: effort });

    if (out.stopCategory === "refusal" || out.stopCategory === "filtered") {
      throw new Error(`Non-retryable stop (${out.stopCategory}): ${out.refusalReason ?? ""}`);
    }
    if (out.stopCategory === "truncated") {
      if (attempt === 0 && maxCompletionTokens < opts.hardCeilingTokens) {
        schemaBudget = Math.min(opts.hardCeilingTokens, schemaBudget * 2);
        effort = "low";
        continue;
      }
      throw new StructuredOutputBudgetError(
        `Truncated at ${maxCompletionTokens} ceiling; split input batch in half.`,
        out.reasoningTokens,
        out.visibleTokens
      );
    }
    return { result: opts.parseAndValidate(JSON.parse(out.rawJsonText)), escalated: attempt > 0 };
  }
  throw new Error("Unreachable");
}
```

## How do you redesign schemas so large array extractions never truncate?

**Quick answer:** Cap array cardinality per API call (`maxItems: 20`), strip verbose repeated key names and prose explanations out of nested objects, constrain strings with concise formatting directives, and fan out multi-page documents using divide-and-conquer chunking rather than monolithic 100-row JSON arrays.

Even with an adaptive budget guard, asking an LLM to extract all `180` line items from a 14-page invoice into a single JSON array will eventually breach any reasonable `hardCeilingTokens` cap. Apply four structural schema optimizations to shrink output token footprints by 45%–70%:

1. **Eliminate chain-of-thought fields inside JSON objects on reasoning models**: Legacy GPT-4 prompts often added a `"step_by_step_reasoning": string` property inside every array item to boost accuracy. On `gpt-5`, `o4-mini`, `claude-sonnet-5.5`, and `gemini-3.1-pro`, that pattern pays **twice**: once for internal reasoning tokens and again for verbose JSON strings across 50 items. Remove prose reasoning fields from the schema and let bounded native thinking handle complex inference.
2. **Shorten repetitive nested property keys**: In a 60-element array, naming four keys `transaction_merchant_canonical_name`, `transaction_iso_currency_code`, `transaction_settlement_category`, and `transaction_confidence_explanation` burns ~28 tokens of boilerplate per item (`1,680` output tokens of pure punctuation and key strings!). Renaming them `merchant`, `currency`, `category`, and `flag` cuts `1,200+` output tokens (`$0.012` per call on `gpt-5` / Sonnet 5.5, or **$24,000/year** across 2M calls) while cutting truncation risk in half.
3. **Replace open-ended strings with strict `enum` unions and `nullable` primitives**: An unconstrained `"status"` string invites `"Pending manual review by billing team due to mismatch"`; an `enum: ["ok", "mismatch", "missing_tax_id"]` caps that field at 1–3 tokens and prevents degenerate sampler loops.
4. **Recursive binary split on `StructuredOutputBudgetError`**: When extracting records from tabular text or transcripts, catch `StructuredOutputBudgetError` at the caller and recursively split the input lines into `[firstHalf, secondHalf]`, running two smaller parallel `gpt-5-mini` (`$0.25/$2.00`) or `gemini-2.5-flash` (`$0.30/$2.50`) calls that finish in half the wall-clock latency with zero truncation.

## How do you verify truncation guards and reasoning telemetry in staging?

**Quick answer:** Force a controlled truncation in staging using `max_completion_tokens: 128` via `curl`, verify your parser throws `StructuredOutputBudgetError` instead of `SyntaxError`, and alert whenever `reasoning_tokens / completion_tokens` exceeds `0.65` on structured JSON routes.

Run this `curl` smoke test against your OpenAI or Gemini staging key to observe the exact `finish_reason: "length"` + `reasoning_tokens` payload your error handler must intercept:

```bash
curl -sS https://api.openai.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "o4-mini",
    "max_completion_tokens": 128,
    "reasoning_effort": "medium",
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "audit_row",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": { "summary": { "type": "string" }, "risk": { "type": "string", "enum": ["low", "high"] } },
          "required": ["summary", "risk"],
          "additionalProperties": false
        }
      }
    },
    "messages": [{"role": "user", "content": "Analyze subtle edge-case race conditions in two-phase commit."}]
  }' | jq '{finish_reason: .choices[0].finish_reason, content_len: (.choices[0].message.content | length), usage: .usage}'
```

Audit every structured extraction endpoint against this five-step checklist before shipping:

1. **Zero blind `JSON.parse()` retries**: Grep your codebase for `JSON.parse` and `zod` inside generic retry helpers (including LangChain, Instructor, or custom queue consumers) and verify `finish_reason` / `stop_reason` / `finishReason` is checked first.
2. **Explicit reasoning effort on extraction**: Confirm pure data-mapping routes pass `reasoning_effort: "low"` on OpenAI, omit or tightly cap `thinking.budget_tokens` on Anthropic, and set `thinkingConfig.thinkingBudget` on Gemini 2.5/3.1.
3. **Non-retryable refusal handling**: Verify `message.refusal !== null` and `stop_reason === "refusal"` exit immediately without wasting retry attempts.
4. **Telemetry split for invisible vs visible tokens**: Dashboard `llm.output.reasoning_tokens` separately from `llm.output.visible_tokens` so silent chain-of-thought inflation never hides inside aggregate `completion_tokens`.
5. **Divide-and-conquer fallback for batch arrays**: Ensure endpoints extracting variable-length arrays split oversized inputs into smaller chunks when hitting `hardCeilingTokens` rather than raising `max_tokens` to `32,768`.
