Testing, Evaluation, and Debugging

How to Test Structured Outputs When the Model Sometimes Deviates

How to Test Structured Outputs When the Model Sometimes Deviates
Learn how to test structured outputs and handle model deviations in AI workflows. This practical guide covers defining deviation types, building strict validators, running deliberate stress probes, measuring retry recovery success rates, and utilizing automated test harnesses to prevent production integration failures caused by invalid JSON or unexpected schema changes.

The first structured-output test suite I wrote had a simple rule: if json.loads succeeded and the required keys were present, the test passed. It stayed green for weeks. Then a production document arrived whose summary contained an extra "confidence" field and a key_points array that mixed strings with short objects. Downstream code that expected a strict shape began throwing. The tests had never seen that deviation because I had never deliberately tried to provoke it.

This post is about testing the ways structured output actually fails. We will take the summarizer and triage workflows from earlier articles, define the deviations we care about, force those deviations to appear, and measure how often our validation and retry logic catches them. The goal is not a perfect model. The goal is a test harness that tells you when the output is no longer safe to hand to the next system.

As always:

Build the smallest useful version, then test what breaks.

What You Will Have Working by the End

  • A clear catalog of the structured-output deviations that matter

  • A small set of probes that deliberately provoke those deviations

  • Validation that distinguishes “recoverable” from “fatal” failures

  • A retry path whose success rate you can measure

  • A short report that shows how often each deviation appears

  • Three practical rules for keeping the tests honest

The Deviations That Actually Break Systems

Most structured-output failures fall into a short list:

  1. Invalid JSON – markdown fences, leading prose, trailing commentary, or truncated output

  2. Missing required keys – the shape is almost right but a field is absent

  3. Extra keys – the model adds helpful fields that downstream code does not expect

  4. Wrong types – a string where an array is required, a number where an enum is required

  5. Constraint violations – an enum value outside the allowed set, an array that is too short or too long

  6. Semantic drift – the JSON is valid and type-correct but the content is wrong for the input

The first five are structural. They can be detected with ordinary validation. The sixth requires either a human judgment or a second model call; we will treat it lightly here and focus on the structural cases that automated tests can catch reliably.

A Strict Validator Worth Testing Against

A documentary close-up of a screen showing Python strict schema validators and deviation error code definitions.

We reuse the schema from the document summarizer and make the validator return structured error codes instead of only a boolean. Error codes make later reporting much easier.

Python

from enum import Enum
from typing import Any

class Deviation(str, Enum):
    INVALID_JSON = "invalid_json"
    MISSING_KEY = "missing_key"
    EXTRA_KEY = "extra_key"
    WRONG_TYPE = "wrong_type"
    CONSTRAINT = "constraint"
    EMPTY_OUTPUT = "empty_output"

REQUIRED_KEYS = ["title", "one_sentence_summary", "key_points", "sentiment"]
ALLOWED_SENTIMENT = {"positive", "neutral", "negative"}

def validate_summary(data: Any) -> list[tuple[Deviation, str]]:
    """Return a list of (deviation, detail) pairs. Empty list means valid."""
    errors: list[tuple[Deviation, str]] = []

    if data is None or data == "":
        return [(Deviation.EMPTY_OUTPUT, "output is empty")]

    if not isinstance(data, dict):
        return [(Deviation.WRONG_TYPE, f"root is {type(data).__name__}, expected dict")]

    for key in REQUIRED_KEYS:
        if key not in data:
            errors.append((Deviation.MISSING_KEY, key))

    extra = set(data.keys()) - set(REQUIRED_KEYS)
    for key in extra:
        errors.append((Deviation.EXTRA_KEY, key))

    if "title" in data and not isinstance(data["title"], str):
        errors.append((Deviation.WRONG_TYPE, "title must be str"))

    if "one_sentence_summary" in data and not isinstance(data["one_sentence_summary"], str):
        errors.append((Deviation.WRONG_TYPE, "one_sentence_summary must be str"))

    if "key_points" in data:
        if not isinstance(data["key_points"], list):
            errors.append((Deviation.WRONG_TYPE, "key_points must be list"))
        else:
            if not (1 <= len(data["key_points"]) <= 5):
                errors.append((Deviation.CONSTRAINT, "key_points length must be 1-5"))
            for i, item in enumerate(data["key_points"]):
                if not isinstance(item, str):
                    errors.append((Deviation.WRONG_TYPE, f"key_points[{i}] must be str"))

    if "sentiment" in data and data["sentiment"] not in ALLOWED_SENTIMENT:
        errors.append((Deviation.CONSTRAINT, f"sentiment '{data['sentiment']}' not allowed"))

    return errors

Every structural problem the model can produce maps to one of these deviation codes.

Probes That Deliberately Provoke Deviations

Ordinary happy-path examples are necessary but not sufficient. You also need inputs and prompt variations that make the model more likely to deviate. Here are four probes I use regularly:

Python

PROBES = [
    {
        "id": "probe-fence",
        "description": "Encourage markdown fences",
        "system_suffix": "Explain your reasoning briefly, then show the JSON inside a markdown code block.",
        "input": "Acme reported strong quarterly results and raised guidance."
    },
    {
        "id": "probe-extra-keys",
        "description": "Encourage helpful extra fields",
        "system_suffix": "Include any additional metadata you think would be useful for a downstream analyst.",
        "input": "The launch was postponed; customers expressed disappointment."
    },
    {
        "id": "probe-empty",
        "description": "Empty document",
        "system_suffix": "",
        "input": ""
    },
    {
        "id": "probe-noise",
        "description": "High-noise input",
        "system_suffix": "",
        "input": "asdf jkl; 12345 !!! qwerty " * 20
    }
]

These probes are not fair tests of the best-case prompt. They are stress tests of the validation and retry layer. If the layer cannot handle them, it will not handle the occasional deviation that appears in production either.

Running the Model and Capturing Deviations

Python

import json
import os
from dotenv import load_dotenv
from anthropic import Anthropic

load_dotenv()
client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))

BASE_SYSTEM = """You are a precise document summarizer.
Return ONLY a valid JSON object with keys:
title, one_sentence_summary, key_points, sentiment.
sentiment must be positive, neutral, or negative.
key_points must be an array of 1-5 strings.
Do not add extra keys. Do not use markdown fences.
"""

def call_summarizer(text: str, system: str) -> tuple[str, dict | None, list]:
    """Return (raw_text, parsed_dict_or_None, list_of_deviations)."""
    response = client.messages.create(
        model="claude-sonnet-5",  # verify current ID in official docs
        max_tokens=512,
        system=system,
        messages=[{"role": "user", "content": f"Summarize:\n\n{text}"}]
    )
    raw = response.content[0].text.strip()

    if not raw:
        return raw, None, [(Deviation.EMPTY_OUTPUT, "empty")]

    try:
        data = json.loads(raw)
    except json.JSONDecodeError as e:
        return raw, None, [(Deviation.INVALID_JSON, str(e))]

    errors = validate_summary(data)
    return raw, data if not errors else None, errors

The function always returns the raw text. When you are debugging, the raw text is more informative than any parsed structure.

Measuring Retry Effectiveness

A retry is only useful if it converts a deviation into a valid result often enough to justify the extra cost. We can measure that directly.

A documentary photo of a developer reviewing terminal logs for AI output retry success rates and error recoveries.

Python

def run_with_retry(text: str, system: str, max_attempts: int = 2) -> dict:
    history = []
    current_system = system
    current_text = text

    for attempt in range(1, max_attempts + 1):
        raw, data, errors = call_summarizer(current_text, current_system)
        history.append({
            "attempt": attempt,
            "raw": raw[:300],
            "errors": [(e.value, d) for e, d in errors],
            "valid": data is not None
        })
        if data is not None:
            return {"ok": True, "data": data, "history": history}

        # Build a corrective follow-up
        error_list = [f"{e.value}: {d}" for e, d in errors]
        current_text = (
            f"Previous output was invalid:\n{json.dumps(error_list)}\n\n"
            f"Return ONLY corrected JSON.\n\nOriginal document:\n{text}"
        )

    return {"ok": False, "data": None, "history": history}

After you run a batch of probes you can compute:

  • How often the first attempt is already valid

  • How often a second attempt recovers a first-attempt failure

  • Which deviation codes are most common

  • Which deviation codes almost never recover on retry

Those numbers tell you whether to invest in a better prompt, a stricter schema, or a stronger decoding constraint (when the platform offers one).

A Minimal Test Report

Python

def run_probe_suite(probes: list[dict]) -> None:
    totals = {d: 0 for d in Deviation}
    recoveries = 0
    first_pass = 0
    total = len(probes)

    for probe in probes:
        system = BASE_SYSTEM + ("\n" + probe["system_suffix"] if probe["system_suffix"] else "")
        result = run_with_retry(probe["input"], system)
        print(f"\n=== {probe['id']}: {probe['description']} ===")
        for h in result["history"]:
            print(f"  Attempt {h['attempt']}: valid={h['valid']} errors={h['errors']}")
            for code, _ in h["errors"]:
                totals[Deviation(code)] = totals.get(Deviation(code), 0) + 1

        if result["history"][0]["valid"]:
            first_pass += 1
        elif result["ok"]:
            recoveries += 1

    print("\n=== Summary ===")
    print(f"First-attempt pass: {first_pass}/{total}")
    print(f"Recovered on retry:  {recoveries}/{total - first_pass if total > first_pass else 0}")
    print("Deviation counts (across all attempts):")
    for d, count in totals.items():
        if count:
            print(f"  {d.value}: {count}")

Run the suite whenever you change the system prompt, the schema, or the model version. The deviation counts are the signal.

Three Practical Rules for Testing Structured Output

  1. Test the validator as hard as you test the model. Feed the validator deliberately malformed objects (extra keys, wrong types, empty lists) and confirm it rejects them. A weak validator makes every other test less meaningful.

  2. Keep a permanent set of deviation probes. Happy-path examples drift toward the prompt you have already optimized. Probes that encourage fences, extra keys, or noisy input stay uncomfortable—and therefore useful.

  3. Measure recovery, not only failure. Knowing that invalid JSON occurs 15 % of the time is interesting. Knowing that a single corrective retry fixes 80 % of those cases is actionable. Track both numbers.

What This Testing Approach Does Not Cover Yet

It does not:

  • Score semantic correctness of the content inside a valid schema

  • Compare cost and latency alongside structural validity

  • Automatically generate new probes from production failures

  • Integrate with a continuous-integration gate

Those topics belong to later testing posts. The goal today is a concrete way to see, count, and recover from the structural deviations that break downstream systems.

Verification Checklist

  1. Run the four probes and confirm you receive a per-attempt breakdown of deviations.

  2. Intentionally weaken the base system prompt and confirm the first-attempt pass rate drops.

  3. Confirm that at least one deviation type (for example extra keys or invalid JSON) appears in the report.

  4. Verify that the retry path sometimes converts a failed first attempt into a valid second attempt.

  5. Feed the validator a hand-crafted object with an extra key and a wrong type; confirm both deviations are reported.

If all five steps pass, you have a working structured-output test harness.

Update Note

Anthropic’s structured-output features and model identifiers continue to evolve. When the platform offers stronger decoding constraints, use them—and still keep the deviation probes. Constraints reduce the frequency of failures; they do not remove the need to measure what happens when a failure still occurs. Always verify the current recommended model ID and output options in the official documentation.

Looking Ahead

The next post combines quality, latency, and cost in a single experiment so you can see the real trade-offs of a prompt or model change. Once you can measure structural validity, adding timing and token counts is a natural next step.

Keep the probe suite. When a production pipeline later starts receiving unexpected fields or truncated JSON, you will already have a fast way to reproduce the deviation and measure whether a change fixed it.

Build the smallest useful version, then test what breaks.

— Caleb Fletcher

Boise, Idaho

Updated · 2026-10-23 11:04
Feedback

No feedback yet — submit the first.

Submit feedback
© 2026 Context & Tools. All rights reserved. data-driven, published weekly ♥