The Bug That Wasn't a Bug
A team ran a nightly pipeline that extracted structured data from legal documents using an LLM. It had been running reliably for two months.
One night it failed. Silent failure - no exception thrown, no alert fired. The output database had been accepting records for six weeks with a damage_cap field stored as a string: "$500,000". Not a number. A string.
Downstream analytics, which assumed an integer, had been silently coercing it to zero. Every risk calculation for those six weeks had a damage cap of $0.
Nobody noticed until a lawyer asked why all their high-value contracts showed zero liability exposure.
The LLM had been returning "$500,000" instead of 500000 for six weeks. Every single record. The application code had accepted it. The database had stored it as VARCHAR. The analytics had silently broken.
There was no bug in the code. There was no validation layer.
direction: down
classes: {
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
llm: "LLM returns damage_cap: \"\$500,000\"" {class: yellow}
app: "Application code: accepts it" {class: grey}
db: "Database: stores it as VARCHAR" {class: grey}
bi: "Analytics: coerces it to 0" {class: red}
out: "Six weeks of \$0 liability exposure" {class: red}
llm -> app -> db -> bi -> out
Every grey box accepted the string without complaint. No layer between the model and the analytics ever asked whether the value was a number.
That failure predates provider strict mode, which would have stopped this particular one at decode time. It's still the right story to start with, because the next one is the same shape with a well-formed number that happens to be wrong.
This is Part 5 of the Harness Engineering series. Part 1 introduced the seven-layer Harness Architecture. This article goes deep on Layer 5 - the Validation and Repair Layer - covering schema validators, semantic checks, repair prompt patterns, and the fail-fast vs. repair decision.
This series grew into a book: Harness Engineering for Production AI Systems. Chapter 7, "Validation and Repair," covers this layer.
17 November 2026: updated for provider structured outputs, which now prevent most shape failures at decode time; split the repair loop so that only shape failures are re-asked, since a content correction teaches the model what passes; added refusal and truncation handling; moved the Instructor example to
from_provider; and gave every tier its own diagram.
What the Validation Layer Actually Does
In Part 1 I described the Validation and Repair Layer as "the difference between a flaky demo and a production system." Let me be more specific.
The model will produce output that breaks your contract. What has changed is which kind. With provider structured outputs turned on - Anthropic's output_config.format and strict tool use, OpenAI's strict structured outputs, Gemini's response schemas - syntax errors, wrong types, missing required fields and invalid enum values are prevented at decode time for schemas the provider supports. Shape failures still get through in specific places:
- Refusals. Anthropic documents
stop_reason: "refusal", where the output may not match the schema. - Truncation. A response that stops at
max_tokensis incomplete. - Unsupported constraints. Anthropic's strict mode doesn't enforce numeric ranges or string lengths, and Gemini silently drops some keywords.
- Models without strict mode, including most self-hosted ones.
Semantic, range and consistency failures were never in scope for decode-time enforcement. A model can return a perfectly typed damage_cap that is ten times what the clause says. That's now where most of this layer's work is.
grid-rows: 1
grid-gap: 16
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
strict: "Provider strict mode prevents" {
label.near: top-center
grid-columns: 1
grid-gap: 8
a: "broken JSON" {class: green}
b: "wrong types, missing fields" {class: green}
c: "invalid enum values" {class: green}
}
yours: "Your validators still catch" {
label.near: top-center
grid-columns: 1
grid-gap: 8
d: "refusals, truncation" {class: red}
e: "ranges and lengths strict mode skips" {class: red}
f: "values that are well-formed and wrong" {class: red}
}
The left column moved to the provider in the last two years. The right column never could, because only your system knows what the right value is.
The Validation Layer has two jobs:
Detection - catch every output that doesn't meet the contract your downstream systems expect. Not occasionally. Every time. Before a single malformed record reaches your database, your API, or your user.
Recovery - when validation fails, either repair the output automatically or fail in a controlled, observable, recoverable way. No silent failures. No downstream corruption. No $0 damage caps propagating for six weeks.
I structure this as a Validation Cascade: three tiers of checks applied in sequence, each catching what the previous cannot. Schema first (structure), semantic second (meaning), business rules third (domain constraints). The cascade runs cheapest-first - which is also why it works at production scale.
The model doesn't need to be perfect. It needs to be correctable. The Validation Layer is what makes correction possible.
The same contract applies upstream of any action a chatbot takes - a banking bot that validates its slots and confidence before acting on an intent is running this layer at the edge of the conversation.
The Three Validation Tiers
Validation is not a single check. It's a hierarchy of checks, applied in order, each tier catching failures the previous one cannot.
Tier 1: Schema Validation
The first check is structural. Does the output conform to the expected shape? Are required fields present? Are types correct? Is the JSON well-formed?
Start by turning on provider strict mode wherever your schema fits within what the provider supports. Then this tier validates everything strict mode doesn't cover: the ranges and lengths it skips, providers and models without it, and the refusal and truncation cases.
This is where Pydantic earns its place. Define your expected output as a Pydantic model and let it do the structural validation for you (checked against Pydantic 2.14):
from decimal import Decimal, InvalidOperationfrom typing import Literalfrom pydantic import BaseModel, Field, field_validator, model_validatorclass LiabilityClause(BaseModel): clause_text: str risk_type: str severity: Literal["low", "medium", "high", "critical"] damage_cap: int | None = Field(ge=0) # integer or null, never a string jurisdiction: str effective_date: str | None @field_validator("damage_cap", mode="before") @classmethod def coerce_damage_cap(cls, v): if isinstance(v, str): # Strip currency symbols and commas before failing cleaned = v.replace("$", "").replace(",", "").strip() try: return int(Decimal(cleaned)) except InvalidOperation: raise ValueError(f"damage_cap must be a number, got: {v!r}") return vclass ExtractionResult(BaseModel): clauses: list[LiabilityClause] document_type: str jurisdiction_detected: str @model_validator(mode="after") def at_least_one_clause(self): if not self.clauses: raise ValueError("Extraction must return at least one clause") return selfNotice the coerce_damage_cap validator. It doesn't just reject "$500,000" - it strips the currency symbol and converts it. This is defensive coercion: attempt to recover the intent before raising an error. The model meant 500000. Get 500000. Log that a coercion happened. Move on.
Defensive coercion handles the long tail of formatting variations without triggering a repair loop for every minor difference. Reserve repair loops for failures that genuinely can't be coerced. With strict mode on, the string never arrives, and the coercion branch is the path for providers and models that run without it. Field(ge=0) is the range check strict mode doesn't do: a negative cap fails here with "Input should be greater than or equal to 0". The Literal already rejects any severity outside the four allowed values, so it needs no validator of its own.
direction: down
classes: {
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
raw: "damage_cap: \"\$500,000\"" {class: yellow}
coerce: "mode=\"before\" validator\nstrip \$ and commas, Decimal -> int" {class: violet}
typed: "damage_cap: 500000" {class: teal}
range: "Field(ge=0)" {class: violet}
out: "" {
grid-rows: 1
grid-gap: 14
ok: "Pass: Tier 2" {class: green}
bad: "Fail: not a number,\nor negative" {class: red}
}
raw -> coerce -> typed -> range
range -> out
Recovery happens before validation. The model's intent is recovered while the value is still raw, and the range check then runs on the typed value, so it judges what the code will actually use.
Tier 2: Semantic Validation
Schema validation checks structure. Semantic validation checks meaning.
A response can be structurally valid and semantically wrong. severity: "low" for a clause that says "contractor bears unlimited liability for all damages" is structurally fine and semantically broken. Tool calls have the same gap, because a strict schema validates the spelling of a call, not the model's choice of values.
class SemanticValidator: def __init__(self, llm): self.llm = llm def validate(self, result: ExtractionResult, source_document: str) -> list[str]: issues = [] for clause in result.clauses: issues.extend(self._check_severity_consistency(clause)) issues.extend(self._check_damage_cap_plausibility(clause, source_document)) return issues def _check_severity_consistency(self, clause: LiabilityClause) -> list[str]: # Rule-based semantic check: unlimited liability should never be "low" unlimited_indicators = [ "unlimited", "all damages", "any and all", "without limit" ] text_lower = clause.clause_text.lower() if any(ind in text_lower for ind in unlimited_indicators): if clause.severity in ("low", "medium"): return [ "Clause mentions unlimited liability but severity is " f"'{clause.severity}'. Expected 'high' or 'critical'." ] return [] def _check_damage_cap_plausibility( self, clause: LiabilityClause, source: str ) -> list[str]: # Use LLM as judge for complex semantic checks if clause.damage_cap is not None and clause.damage_cap > 0: prompt = ( f"Source clause: {clause.clause_text}\n\n" f"Extracted damage_cap: ${clause.damage_cap:,}\n\n" "Does the extracted damage cap accurately reflect the source clause? " "Reply with only 'yes' or 'no'." ) response = self.llm.call(prompt).strip().lower() if response == "no": return [ f"Damage cap ${clause.damage_cap:,} appears inconsistent " "with source clause text." ] return []Semantic validation has two modes: rule-based (fast, deterministic, covers known failure patterns) and LLM-as-judge (flexible, catches novel failures, slower and more expensive). Use rule-based for common patterns you can enumerate. Use LLM-as-judge only for complex semantic consistency checks that can't be rule-encoded, and only when the cost of a false negative justifies the additional LLM call.
The messages these checks return are for your logs and your reviewers. "Expected 'high' or 'critical'" is exactly what a person needs to see. It's also exactly what the model must not see in a repair prompt, for reasons the repair section below explains.
direction: down
classes: {
teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
}
clause: "Typed clause from Tier 1" {class: teal}
checks: "" {
grid-rows: 1
grid-gap: 16
rule: "Rule-based\n'unlimited' + severity low?\nfast, free, deterministic" {class: blue}
judge: "LLM-as-judge\ndoes the cap match the text?\none extra call per clause" {class: violet}
}
issues: "Issues: to the log and the reviewer" {class: grey}
clause -> checks
checks -> issues
Use the left box for every pattern you can name, and the right box only where a rule can't express the check. Every judge call is another model call that can itself be wrong.
Tier 3: Business Rule Validation
The third tier enforces constraints that are specific to your domain and invisible to the model.
class BusinessRuleValidator: def __init__(self, db): self.db = db def validate(self, result: ExtractionResult, document_id: str) -> list[str]: issues = [] # Cross-reference: jurisdiction must be in our supported set supported = self.db.get_supported_jurisdictions() if result.jurisdiction_detected not in supported: issues.append( f"Jurisdiction '{result.jurisdiction_detected}' not in supported set. " f"Supported: {supported}" ) # Uniqueness: no duplicate clause_text within same document seen_texts = set() for clause in result.clauses: if clause.clause_text in seen_texts: issues.append( f"Duplicate clause text detected: {clause.clause_text[:50]}..." ) seen_texts.add(clause.clause_text) # Referential integrity: document_type must match DB record doc_type = self.db.get_document_type(document_id) if doc_type and doc_type != result.document_type: issues.append( f"Extracted document_type '{result.document_type}' " f"doesn't match DB record '{doc_type}'" ) return issuesBusiness rule validation is where domain knowledge lives - the constraints your model cannot know because they exist in your systems, not in the document being processed.
direction: down
classes: {
teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
}
result: "ExtractionResult that passed Tiers 1 and 2" {class: teal}
rules: "" {
grid-rows: 1
grid-gap: 12
j: "Jurisdiction in\nsupported set?" {class: blue}
d: "No duplicate\nclause text?" {class: blue}
t: "document_type matches\nthe DB record?" {class: blue}
}
db: "Your database: the facts the model never saw" {class: grey}
result -> rules
db -> rules
The grey box is what makes this a separate tier. Two of the three checks compare the output against data that exists only in your systems, and no prompt or stronger model could have satisfied those by itself.
The Repair Loop Pattern
When validation fails and defensive coercion can't recover the output, you have a choice: fail fast or repair.
Fail fast when:
- The failure is unrecoverable (the model returned HTML instead of JSON)
- The failure has cascaded past the point where a retry would be coherent
- You've already retried and the same failure recurs
- The cost of retry exceeds the value of the result
Repair when:
- The failure is specific and correctable (wrong type on a known field)
- The schema violation can be described precisely in a prompt
- The model is likely to succeed on a targeted correction request
- The downstream cost of failure exceeds the cost of an additional LLM call
Which failure you're repairing matters as much as whether to repair. Shape failures - broken JSON, a wrong type, a missing field - are safe to re-ask with the error attached. The error says only what format is expected, and that's information the model should have. Content failures - a severity that contradicts the clause, a cap that doesn't match the text, a jurisdiction you don't support - are different. A re-ask that names the expected value teaches the model what passes, so the retry that passes may be a guess rather than a correction. The later part on coached repairs measures exactly that. For content failures, use a deterministic fix where one exists, narrow to a closed question, or defer to a person.
The repair loop below therefore only re-asks for shape failures. Two stop reasons skip the re-ask entirely: a refusal, which no rephrasing should talk the model out of, and a truncation, where the fix is a higher max_tokens rather than a correction. The llm here is a stand-in for your client wrapper. Its call returns the reply text and the provider's stop reason.
import jsonfrom pydantic import ValidationErrorclass MaxRetriesExceeded(Exception): passclass NotRepairable(Exception): passdef validated_extraction( prompt: str, document: str, schema: type[BaseModel], llm, max_retries: int = 3,) -> BaseModel: current_prompt = prompt last_error = None for attempt in range(max_retries): reply = llm.call(current_prompt + f"\n\nDocument:\n{document}") # Two stop reasons that a re-ask cannot fix if reply.stop_reason == "refusal": raise NotRepairable("model refused: defer to a person, don't re-ask") if reply.stop_reason == "max_tokens": raise NotRepairable("output truncated: retry with a higher max_tokens") # Shape failures: re-ask with the error, which is safe here try: parsed = json.loads(reply.text) except json.JSONDecodeError as e: last_error = f"Invalid JSON: {e}" current_prompt = build_schema_repair_prompt(prompt, reply.text, last_error) continue try: return schema.model_validate(parsed) except ValidationError as e: last_error = format_validation_errors(e) current_prompt = build_schema_repair_prompt(prompt, reply.text, last_error) raise MaxRetriesExceeded( f"Validation failed after {max_retries} attempts. Last error: {last_error}" )def build_schema_repair_prompt(original_prompt: str, bad_output: str, errors: str) -> str: return ( f"{original_prompt}\n\n" f"Your previous response contained validation errors:\n{errors}\n\n" f"Your previous response was:\n{bad_output}\n\n" "Please correct these specific errors and return valid JSON. " "Do not change any fields that were correct." )def format_validation_errors(e: ValidationError) -> str: lines = [] for error in e.errors(): field = " -> ".join(str(loc) for loc in error["loc"]) lines.append(f"- Field '{field}': {error['msg']} (got: {error.get('input')!r})") return "\n".join(lines)Run against a fake client that first returns prose, then a severity of "severe", then valid JSON, the loop succeeds on its third call, with damage_cap coerced to 500000. The repair prompt for the third attempt carried only a shape error: Pydantic's own message that severity should be one of the four allowed values, with the 'severe' it received.
Two implementation details that matter enormously:
"Do not change any fields that were correct." Without this instruction, the model often fixes the errored field but introduces new errors in previously correct fields. Constrain the repair to the failing fields only.
Back off on API errors, not on validation failures. A delay doesn't change what the model writes. The re-ask already differs from the first prompt because it carries the error. Exponential backoff with jitter belongs on 429s and 5xx responses (Part 6). Cap repair attempts per failure class, and count every attempt against the run's budget.
direction: down
classes: {
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
}
fail: "A validation failure" {class: yellow}
kind: "What failed?" {class: violet}
paths: "" {
grid-rows: 1
grid-gap: 14
shapef: "Shape: JSON, type, field\nre-ask with the error" {class: blue}
content: "Content: wrong value\nfix, narrow, or defer;\nnever name the answer" {class: grey}
stop: "Refusal or truncation\nno re-ask" {class: red}
}
fail -> kind
kind -> paths
Only the blue path sends the model a correction. The grey path keeps the answer out of the prompt, because a model that is told what passes will produce it, whether or not it's true.
Native Structured Outputs and Instructor
Part 1 names Pydantic and Instructor as common options for this layer, paired with native structured outputs. You often don't need your own parsing loop at all.
On the Claude API, the SDK's messages.parse takes a Pydantic model, sends its schema as a structured output, and hands back a validated instance. The shape is enforced at decode time, so the parser never has to recover from prose:
from anthropic import Anthropicclient = Anthropic()message = client.messages.parse( model="claude-sonnet-5-5", max_tokens=2000, messages=[{"role": "user", "content": f"Extract liability clauses:\n{document}"}], output_format=ExtractionResult, # your Pydantic model)if message.stop_reason in ("refusal", "max_tokens"): ... # not repairable by re-asking: defer, or retry with more tokensresult = message.parsed_output # a validated ExtractionResultInstructor wraps the same idea with a provider-neutral client and an automatic retry loop. Its documented entry point is now from_provider:
import instructorclient = instructor.from_provider("anthropic/claude-sonnet-5-5")result = client.create( response_model=ExtractionResult, # your Pydantic model messages=[{"role": "user", "content": f"Extract liability clauses:\n{document}"}], max_tokens=2000, max_retries=3, # re-asks with the validation error)Both snippets need an API key, so they weren't executed here. Their signatures were checked against anthropic 2.9.0 and instructor 1.17.0.
Instructor's retries re-ask with the validation error - the shape-failure pattern above. That's safe as long as your Pydantic model carries only shape constraints. Keep content checks out of the model's validators and run them as Tiers 2 and 3, where a failure goes to a fix, a narrowed question or a person instead of back to the model.
grid-rows: 1
grid-gap: 12
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
}
provider: "Provider strict mode\nshape at decode time" {class: green}
parse: "messages.parse or Instructor\nparsing, typed result, shape retries" {class: blue}
own: "Your Tiers 2 and 3\nmeaning and domain rules" {class: violet}
Each box owns one job. The first two can be bought, and the third is the part only you can write.
The Named Pattern: Validation Cascade
I call the three-tier structure the Validation Cascade: schema first, semantic second, business rules third.
The cascade runs in this order for a reason. Schema validation is cheap and fast - it runs entirely in memory with no LLM calls. Semantic validation is more expensive - it may involve an LLM-as-judge call. Business rule validation requires database access.
Run the cheapest check first. Gate the expensive checks behind the cheap ones.
A schema failure short-circuits the cascade - no point running semantic validation on output that can't even be parsed. A schema pass but semantic failure short-circuits business rule validation. Only output that passes all upstream tiers reaches the final tier.
This cascade structure means your expensive checks only run on output that has already cleared the cheap ones - dramatically reducing the cost of comprehensive validation.
grid-rows: 1
grid-gap: 12
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
}
t1: "Tier 1: schema\nin memory, microseconds" {class: green}
t2: "Tier 2: semantic\nrules, maybe a judge call" {class: blue}
t3: "Tier 3: business\ndatabase lookups" {class: violet}
t1 -> t2: "pass"
t2 -> t3: "pass"
Cost rises left to right, and each arrow only fires on a pass. So the most expensive box sees the fewest records.
The Full Validation Pipeline
The Validation Cascade and the Repair Loop work together as a single pipeline. The cascade decides what's wrong. The repair loop decides what to do about it.
grid-rows: 6
grid-columns: 2
grid-gap: 40
classes: {
yellow: {style: {fill: "#FACC15"; stroke: "#CA8A04"; font-color: "#2C2C2A"}}
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
teal: {style: {fill: "#4B0082"; stroke: "#3A0066"; font-color: "#FFFFFF"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
red: {style: {fill: "#FB923C"; stroke: "#EA580C"; font-color: "#2C2C2A"}}
}
raw: "1. LLM output (strict mode where supported)" {class: yellow}
stop: "Refusal or truncation:\ndefer, or retry with more tokens" {class: red}
coerce: "2. Defensive coercion" {class: teal}
retry: "LLM retry with the shape error\n(back to 1, retries capped)" {class: yellow}
t1: "3. Tier 1: schema" {class: green}
fast: "Retries used up:\nfail fast" {class: red}
t2: "4. Tier 2: semantic" {class: green}
content: "Content failure:\nfix, narrow, or defer" {class: grey}
t3: "5. Tier 3: business rules" {class: green}
content3: "Content failure:\nfix, narrow, or defer" {class: grey}
out: "6. Validated output -> downstream" {class: blue}
spacer: "" {style.opacity: 0}
raw -> stop
raw -> coerce -> t1
t1 -> retry: "shape failure"
retry -> fast
t1 -> t2: "pass"
t2 -> content
t2 -> t3: "pass"
t3 -> content3
t3 -> out: "pass"
Four things to note in this diagram. First, defensive coercion runs before Tier 1, so a value that can be coerced never enters the repair loop. Second, only Tier 1 has a path back to the model: a repaired output re-enters at the top and runs the full cascade again. Third, Tiers 2 and 3 have no retry arrow at all. Their failures go to a deterministic fix, a narrowed question or a person, because a re-ask that names the expected value turns the retry into a coached guess. Fourth, the retry is yellow, like the original output, because it is still a probabilistic call.
What Observability Looks Like for This Layer
Validation failure rate by tier - what fraction of outputs fail at schema vs. semantic vs. business rule? A high schema failure rate signals prompt drift or model degradation. A high semantic failure rate signals the model is misunderstanding the task. A high business rule failure rate signals your domain constraints are tighter than the model's outputs.
Repair success rate - of outputs that fail validation and enter the repair loop, what fraction succeed on retry? Split it by failure class. A low shape-repair rate means your repair prompts or your schema need work. A high repair rate on content failures is a warning, not a success: if content failures are reaching the model at all, it is probably being coached toward answers that pass.
grid-rows: 2
grid-columns: 4
grid-gap: 12
classes: {
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
grey: {style: {fill: "#F3F4F6"; stroke: "#D1D5DB"; font-color: "#2C2C2A"}}
}
a: "Each tier" {class: violet}
b: "Repair loop" {class: violet}
c: "Coercion" {class: violet}
d: "Retries" {class: violet}
m1: "Failure rate by tier" {class: grey}
m2: "Repair rate by\nfailure class" {class: grey}
m3: "Coercion rate by field" {class: grey}
m4: "Retries per success" {class: grey}
Defensive coercion rate - how often does Pydantic coerce a value rather than reject it? A rising coercion rate on a specific field signals the model is developing a systematic formatting habit that differs from your schema. Address it in the prompt before it becomes a repair loop dependency.
Retry distribution - what fraction of successes required 1 retry vs. 2 vs. 3? If most successes require 3 retries, your base prompt needs work. If most succeed on first attempt, your validation is healthy.
What to Build First
First: Turn on provider strict mode wherever your schema fits what the provider supports. It is the cheapest change on this list and removes most shape failures outright.
Second: Pydantic models for all structured outputs. If you're calling json.loads() without Pydantic validation on the result, you have unvalidated LLM output in production. Add Pydantic models today, with messages.parse or Instructor to do the parsing and shape retries.
Third: Defensive coercion for common type mismatches. Add field validators for the types the model consistently gets wrong: currency strings to integers, date strings to date objects, percentage strings to floats.
Fourth: Shape-only repair prompts. Write targeted repair prompts for your most common shape failures, explaining the correct format explicitly. Content failures don't go back to the model at all.
Fifth: Rule-based semantic validators. Add checks for the semantic failures you can enumerate from your domain knowledge. Unlimited liability with low severity. Negative damage caps. Contradictory date ranges.
Sixth: LLM-as-judge for complex semantic validation. Add LLM-as-judge checks only for semantic failures you cannot encode as rules. Be selective - each LLM-as-judge check adds one model call per field it judges.
grid-columns: 1
grid-gap: 8
classes: {
green: {style: {fill: "#4ADE80"; stroke: "#16A34A"; font-color: "#2C2C2A"}}
blue: {style: {fill: "#38BDF8"; stroke: "#0EA5E9"; font-color: "#2C2C2A"}}
violet: {style: {fill: "#6F00FF"; stroke: "#5500CC"; font-color: "#FFFFFF"}}
}
s1: "1. Provider strict mode" {class: green}
s2: "2. Pydantic models + parse/Instructor" {class: green}
s3: "3. Defensive coercion" {class: blue}
s4: "4. Shape-only repair prompts" {class: blue}
s5: "5. Rule-based semantic checks" {class: violet}
s6: "6. LLM-as-judge, selectively" {class: violet}
The green steps make shape a solved problem. The blue steps handle what strict mode leaves behind, and the violet steps are where the work moves once shape is reliable.
The Principle
The model is a probabilistic system. Probabilistic systems produce incorrect outputs at some non-zero rate. That rate is not zero even for the best models on the best prompts.
Your validation layer is what transforms a probabilistic system into a reliable one.
Not by making the model perfect - that's not the goal and not achievable. By catching every deviation from the contract your downstream systems depend on, and either correcting it automatically or failing in a way that is observable, recoverable, and auditable.
The $0 damage caps ran for six weeks because there was no validation layer. There was no mechanism to catch the deviation, no alert when it started, no visibility into how long it had been happening.
Silent failures are the most expensive kind. The Validation Cascade makes LLM failures loud, caught, and correctable - before they reach your database, your users, or your lawyers.
What's Next in This Series
- Part 1: Harness Engineering - The Missing Layer - The full seven-layer Harness Architecture overview
- Part 2: Normalization and Input Defense - Prompt injection, input sanitization, and multi-surface consistency
- Part 3: Context Engineering - Memory architectures, retrieval strategies, and context compression
- Part 4: Gated Execution - Policy engines, human-in-the-loop design, and dry-run patterns
- Part 6: Retry, Fallback, and Circuit Breaking - Building resilient LLM infrastructure that survives model outages and latency spikes
- Part 7: State Management for Agentic Systems - Checkpoint-resume strategies, cross-session memory, and durable state for long-running agents
- Part 8: Deterministic Constraint Systems - Building tool registries and action manifests that prevent hallucinated actions in agentic systems
Going deeper: Chapter 7 of the book
This is Part 5 of the Harness Engineering series, which grew into Harness Engineering for Production AI Systems. This layer became Chapter 7, "Validation and Repair," which declares the Repair Ladder as a TOML policy file, walks through three narrowing shapes from dropping optional fields to asking a closed question, uses the decision log to tell a stale schema from a struggling model, and explains why the ladder's loop belongs inside a graph node rather than on a graph edge.
The code for that chapter is the ch07-validation-repair tag of the companion repository. Its tests need no model and no API key.
For a chapter-length treatment on this blog, including where it departs from the book, see LLM Output Repair: A Re-ask That Passes Can Still Be a Guess, Part 7 of the chapter-by-chapter guide to the book.
References
-
Liu, J. Instructor: Structured outputs for LLMs. https://github.com/567-labs/instructor
-
Pydantic. Pydantic documentation. https://pydantic.dev/docs/validation/latest/get-started/
-
Ouyang, L., Wu, J., Jiang, X., et al. (2022). Training language models to follow instructions with human feedback. arXiv:2203.02155. https://arxiv.org/abs/2203.02155 (background)
-
Shinn, N., Cassano, F., Berman, E., Gopinath, A., Narasimhan, K., & Yao, S. (2023). Reflexion: Language Agents with Verbal Reinforcement Learning. arXiv:2303.11366. https://arxiv.org/abs/2303.11366 (background)
-
Zheng, L., Chiang, W. L., Sheng, Y., et al. (2023). Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena. NeurIPS 2023. https://arxiv.org/abs/2306.05685
-
Chase, H. (2022). LangChain. https://github.com/langchain-ai/langchain (background)
-
Anthropic. Structured outputs. https://platform.claude.com/docs/en/build-with-claude/structured-outputs
-
Kumar, R. (2026). Harness Engineering for Production AI Systems. Chapter 7, "Validation and Repair." https://harness.ranjankumar.in/
-
OpenAI. Structured outputs. https://developers.openai.com/api/docs/guides/structured-outputs
-
Google. Gemini API: structured output. https://ai.google.dev/gemini-api/docs/structured-output
-
Instructor.
from_provider. https://python.useinstructor.com/concepts/from_provider/
Related Articles
- Normalization and Input Defense: Hardening the Entry Point of Your LLM System
- Harness Engineering: The Missing Layer Between LLMs and Production Systems
- Retry, Fallback, and Circuit Breaking: Building LLM Infrastructure That Survives Outages
- Context Engineering: What the Model Sees Is What the Model Does






