Task Statement 4.4·Domain 4 — 20% of exam
Validation, Retry, and Feedback Loops
Implement validation, retry, and feedback loops for extraction quality
Official Exam Guide Objectives
Task 4.4: Implement validation, retry, and feedback loops for extraction quality
Knowledge of
- Retry-with-error-feedback: appending specific validation errors to the prompt on retry to guide the model toward correction
- The limits of retry: retries are ineffective when the required information is simply absent from the source document (vs format or structural errors)
- Feedback loop design: tracking which code constructs trigger findings (detected_pattern field) to enable systematic analysis of dismissal patterns
- The difference between semantic validation errors (values don't sum, wrong field placement) and schema syntax errors (eliminated by tool use)
Skills in
- Implementing follow-up requests that include the original document, the failed extraction, and specific validation errors for model self-correction
- Identifying when retries will be ineffective (e.g., information exists only in an external document not provided) versus when they will succeed (format mismatches, structural output errors)
- Adding detected_pattern fields to structured findings to enable analysis of false positive patterns when developers dismiss findings
- Designing self-correction validation flows: extracting "calculated_total" alongside "stated_total" to flag discrepancies, adding "conflict_detected" booleans for inconsistent source data
What You Need to Know
Extraction systems fail in production, and reliably: documents arrive shaped unexpectedly, figures fail to reconcile, values land in the wrong field. What distinguishes a robust pipeline is not the absence of those failures but what happens next. The validation-retry pattern converts them into a workflow that repairs itself.
Retry-with-Error-Feedback
A retry worth making carries three things back to the model:
- The original document — there is nothing to re-read without it, and a retry is a re-reading
- The failed extraction — its own previous answer, so the correction is targeted rather than a fresh attempt
- The specific validation error — the one element that distinguishes this from simply asking again
// Retry with error feedback
const retryMessages = [
{
role: "user",
content: `Original document:\n${originalDocument}\n\n` +
`Your extraction:\n${JSON.stringify(failedExtraction)}\n\n` +
`Validation error: Line items sum to £450 but stated_total is £500. ` +
`Please re-extract, ensuring all line items are captured.`
}
];The gap between this and a bare retry is large. Re-running the same request against the same document invites the same reading of it, so the same mistake comes back. Naming the discrepancy gives the model somewhere to direct its attention — hunting for the line item it missed, checking which field a value landed in, redoing the arithmetic.
The Retry Effectiveness Boundary
This is the concept the exam tests most aggressively in this task statement. Retries have a clear effectiveness boundary:
Retries ARE effective for:
- Dates rendered in the wrong convention, or currency written inconsistently between fields
- Output whose shape is wrong — values nested at the wrong level, or assigned to the wrong property
- A value that is in the document and ended up under the wrong key
- Arithmetic that fails because a line item was skipped on the first pass
Retries are NOT effective for:
- Anything the source simply does not state
- Values that live in a second document nobody supplied
- Fields that would require knowledge from outside the material provided
The line between the two lists is whether the answer is present in what the model was given. Everything above it is a reading failure and re-reading can correct it; everything below it is an absence, and no number of attempts conjures a department name out of a document that never mentioned one. Items will offer a retry for both situations. For the second, the correct response is to route the extraction to human review, or to return null where the schema permits it.
Self-Correction Flow Design
Some validation can live inside the schema rather than in the logic that inspects its output:
calculated_total vs stated_total: Ask for both — the sum the model derives from the line items, and the total the document asserts. A disagreement between two fields is then visible in the extraction itself, with no external arithmetic required to notice it.
{
"line_items": [
{ "description": "Widget A", "amount": 150.00 },
{ "description": "Widget B", "amount": 300.00 }
],
"calculated_total": 450.00,
"stated_total": 500.00,
"total_discrepancy": true
}conflict_detected booleans: Where a source may contradict itself, give the model a field to say so. A document stating "payment due: 30 days" in one place and "payment terms: net 60" in another should surface both readings with conflict_detected: true, rather than the model quietly selecting whichever it encountered first.
detected_pattern Fields
Review and analysis pipelines benefit from recording what triggered each finding, not only the finding itself:
{
"finding": "Potential SQL injection vulnerability",
"severity": "critical",
"detected_pattern": "string concatenation in SQL query",
"file": "user_service.py",
"line": 42
}That field turns dismissals into data. Group the findings developers reject by detected_pattern and the weak rules identify themselves — if everything triggered by "variable shadowing in nested scope" is being waved through, that pattern's prompt needs work rather than the reviewers needing persuasion. Extract, validate, gather what was dismissed, refine, repeat.
Schema Syntax Errors vs Semantic Validation Errors
The exam distinguishes between these two error categories:
Schema syntax errors — Malformed JSON, missing required fields, wrong data types. Eliminated entirely by tool_use with JSON schemas (covered in Task Statement 4.3).
Semantic validation errors — Structurally valid output carrying wrong values: totals that do not reconcile, dates in an impossible order, data in the wrong field. Nothing about the schema can detect these, because each one satisfies it. They need validation logic written separately, and they are what retry loops exist for.
These two task statements deliberately overlap, and the point being tested is the boundary between them: tool_use closes the first category completely and the second not at all.
Deep Dive
The API already retries malformed tool calls internally
Before you write a single line of retry logic, the Claude API has a baked-in version of this pattern: "If a tool request is invalid or missing parameters, Claude will retry 2-3 times with corrections before apologizing to the user." This is the same retry-with-error-feedback principle operating one layer down — the API surfaces its own validation error to the model and lets it self-correct. Your application-level retry loop for semantic errors (sums, field placement, fabrication) is the same mechanism extended to checks the API cannot perform on its own.
Sourceplatform.claude.com › handle-tool-callsfetched 2026-07-30
is_error is the general-purpose feedback channel
The mechanism for reporting a failure back to the model already exists in the Messages API: "If the tool itself throws an error during execution... you can return the error message in the content along with \"is_error\": true" and "Claude will then incorporate this error into its response to the user." Retry-with-error-feedback for extraction validation is a direct application of this same contract — instead of a tool execution failure, the "error" you report is a semantic validation failure, delivered as specific text in the next user turn rather than a generic is_error tool_result.
Sourceplatform.claude.com › handle-tool-callsfetched 2026-07-30
Rules-based feedback outranks vague or judge-based feedback
Anthropic's Agent SDK guidance ranks feedback quality explicitly: "The best form of feedback is providing clearly defined rules for an output, then explaining which rules failed and why. Code linting is an excellent form of rules-based feedback. The more in-depth in feedback the better." This is precisely the shape of "Line items sum to £450 but stated_total is £500" — a specific rule, a specific violation, not a generic "validation failed." The same guidance places another common alternative near the bottom of the hierarchy: judging output with a second LLM call is "generally not a very robust method, and can have heavy latency tradeoffs" — reinforcing why this task statement favours deterministic, rule-based validation logic over an LLM re-grading its own extraction.
Sourceclaude.com › building-agents-with-the-claude-agent-sdkfetched 2026-07-30
Self-verification is valuable — but only inside the fixable boundary
The Agent SDK blog frames self-checking as a reliability multiplier: "Agents that can check and improve their own output are fundamentally more reliable — they catch mistakes before they compound." Read alongside this task's retry-effectiveness boundary, the claim only holds for errors the model can actually correct by re-examining information it already has access to (the source document). It is not a claim that self-checking can conjure data the source document never contained — that failure mode still routes to human review, not another retry.
Sourceclaude.com › building-agents-with-the-claude-agent-sdkfetched 2026-07-30
Repeated failures on the same pattern call for a formal rule, not another retry
For findings that fail repeatedly in the same recognisable way — the exact scenario detected_pattern tracking is built to surface — the documented fix is architectural, not another retry attempt: "If your agent fails at a task repeatedly, can you add a formal rule in your tool calls to identify and fix the failure?" This is the systematic-improvement half of the loop: detected_pattern data tells you which pattern keeps failing or getting dismissed; the fix is a prompt or schema change for that pattern, not persistence with the retry loop.
Sourceclaude.com › building-agents-with-the-claude-agent-sdkfetched 2026-07-30
Quick Reference
| Item | Value / rule |
|---|---|
| Retry message must include | Original document + failed extraction + specific validation error |
| API's own tool-call retry behaviour | Retries invalid/missing-parameter tool calls 2-3 times with corrections before apologising |
| is_error feedback contract | Return content + "is_error": true; Claude incorporates it into its response |
| Best feedback form (documented ranking) | Clearly defined rules + which rule failed and why (e.g. code linting) |
| Weakest feedback form (documented ranking) | LLM-as-judge — "not a very robust method," heavy latency tradeoffs |
| Retries ARE effective for | Format mismatches, structural errors, misplaced values, missed line items |
| Retries are NOT effective for | Information genuinely absent from the source document |
| Unfixable extraction | Flag for human review or return null — do not keep retrying |
| Self-correction schema fields | calculated_total vs stated_total, total_discrepancy, conflict_detected |
| Systematic improvement signal | detected_pattern field + dismissal-rate analysis |
| Repeated pattern failures | Add a formal rule / refine the prompt for that pattern — not another retry |
| Schema syntax errors | Eliminated by tool_use (Task 4.3) |
| Semantic validation errors | Require validation logic and retry loops (this task) |
Exam Traps
Practice Scenario
Your extraction pipeline validates that line item amounts sum to the stated total. For Document A, the calculated sum is £450 but the stated total is £500. For Document B, the 'department' field is missing entirely from the source text. Which retry strategy is correct?
Build Exercise
Build a Validation-Retry Loop for Document Extraction
Difficulty: Advanced (3/4)
60 minutes
- Define an extraction tool with calculated_total and stated_total fields, a conflict_detected boolean, and detected_pattern fields for tracking which constructs trigger findings
Why: Self-correction fields like calculated_total vs stated_total enable automatic discrepancy detection without external logic. conflict_detected booleans and detected_pattern fields create the data foundation for systematic prompt improvement.
You should see: A JSON schema with separate calculated_total and stated_total number fields, a total_discrepancy boolean, a conflict_detected boolean, and a detected_pattern string field on each finding in the line_items array.
- Implement validation logic that checks: field completeness, numerical consistency (calculated sum matches stated total), enum validity, and date ordering
Why: Semantic validation catches errors that tool_use cannot. The exam distinguishes schema syntax errors (eliminated by tool_use) from semantic errors (wrong sums, misplaced values) that require validation logic and retry loops.
You should see: A validation function that returns an array of specific, actionable error messages. Each error should state what was expected versus what was found, not just that validation failed.
- Build the retry loop: on validation failure, construct a follow-up message containing the original document, the failed extraction, and the specific validation error
Why: Retry-with-error-feedback is dramatically more effective than naive retries. Without the specific error, the model has no guidance and typically reproduces the same mistake. With the error, the model can target its self-correction.
You should see: A retry message that includes all three elements: the original document text, the JSON of the failed extraction, and the specific validation error string. The model should produce a corrected extraction on retry.
- Test with 5 documents: 2 with fixable errors (misplaced values, wrong totals) and 3 with unfixable errors (absent information) — verify the loop retries only fixable cases
Why: The retry effectiveness boundary is the most aggressively tested concept in this task statement. Retries fix format mismatches and structural errors but cannot create information absent from the source. The exam presents both scenarios and expects you to identify which is fixable.
You should see: The 2 fixable documents succeed after 1-2 retries with corrected totals or field placements. The 3 unfixable documents are correctly identified as having absent information and flagged for human review rather than retried.
- Log detected_pattern data for each finding and analyse which patterns are most frequently dismissed to identify prompt refinement priorities
Why: detected_pattern fields create a systematic improvement loop. When developers consistently dismiss findings triggered by a specific pattern, that pattern likely needs prompt refinement. This turns dismissal data into actionable prompt improvement priorities.
You should see: A log or table showing each detected_pattern, its frequency, its dismissal rate, and a prioritised list of patterns needing prompt refinement. Patterns with high dismissal rates should be at the top.
Sources
- Claude Certified Architect Foundations Exam Guide — Task Statement 4.4 — Anthropic
- Tool Use (Function Calling) — Anthropic
- Building with Claude API (Skilljar) — Anthropic
- Handling Tool Calls — Anthropic
- Building Agents with the Claude Agent SDK — Anthropic
Appendix A — Build Exercise Step Hints
Progressive hints revealed by the "Stuck? Get a nudge" control on each step.
Step 1. Define an extraction tool with calculated_total and stated_total fields, a conflict_detected boolean, and detected_pattern fields for tracking which constructs trigger findings
Why: Self-correction fields like calculated_total vs stated_total enable automatic discrepancy detection without external logic. conflict_detected booleans and detected_pattern fields create the data foundation for systematic prompt improvement.
You should see: A JSON schema with separate calculated_total and stated_total number fields, a total_discrepancy boolean, a conflict_detected boolean, and a detected_pattern string field on each finding in the line_items array.
Stuck? Get a nudge
Step 2. Implement validation logic that checks: field completeness, numerical consistency (calculated sum matches stated total), enum validity, and date ordering
Why: Semantic validation catches errors that tool_use cannot. The exam distinguishes schema syntax errors (eliminated by tool_use) from semantic errors (wrong sums, misplaced values) that require validation logic and retry loops.
You should see: A validation function that returns an array of specific, actionable error messages. Each error should state what was expected versus what was found, not just that validation failed.
Stuck? Get a nudge
Step 3. Build the retry loop: on validation failure, construct a follow-up message containing the original document, the failed extraction, and the specific validation error
Why: Retry-with-error-feedback is dramatically more effective than naive retries. Without the specific error, the model has no guidance and typically reproduces the same mistake. With the error, the model can target its self-correction.
You should see: A retry message that includes all three elements: the original document text, the JSON of the failed extraction, and the specific validation error string. The model should produce a corrected extraction on retry.
Stuck? Get a nudge
Step 4. Test with 5 documents: 2 with fixable errors (misplaced values, wrong totals) and 3 with unfixable errors (absent information) — verify the loop retries only fixable cases
Why: The retry effectiveness boundary is the most aggressively tested concept in this task statement. Retries fix format mismatches and structural errors but cannot create information absent from the source. The exam presents both scenarios and expects you to identify which is fixable.
You should see: The 2 fixable documents succeed after 1-2 retries with corrected totals or field placements. The 3 unfixable documents are correctly identified as having absent information and flagged for human review rather than retried.
Stuck? Get a nudge
Step 5. Log detected_pattern data for each finding and analyse which patterns are most frequently dismissed to identify prompt refinement priorities
Why: detected_pattern fields create a systematic improvement loop. When developers consistently dismiss findings triggered by a specific pattern, that pattern likely needs prompt refinement. This turns dismissal data into actionable prompt improvement priorities.
You should see: A log or table showing each detected_pattern, its frequency, its dismissal rate, and a prioritised list of patterns needing prompt refinement. Patterns with high dismissal rates should be at the top.
Stuck? Get a nudge
Appendix B — Interactive Study Prompts
Two prompts to paste into Claude. B1 drills the judgement the exam actually measures; B3 reviews the code you wrote for the Build Exercise above. The exam simulator between them is the interactive quiz on this page.
B1. Concept Check — Discrimination Drill
You are examining me for the Claude Certified Architect – Foundations (CCAR-F) exam, Domain 4: Prompt Engineering & Structured Output (20% of the exam), Task Statement 4.4: Validation, Retry and Feedback Loops. Use British English throughout.
What this exam actually measures. Not one item on the official exam asks what something is. Every item drops you into a production system that is already misbehaving, offers four defensible engineering responses, and asks which is best. The skill being tested is proportionality: fix the root cause with the cheapest instrument that gives the guarantee the situation demands. So do not quiz me on definitions. Make me choose between options that are both defensible, then attack whatever I chose.
How to run this session.
- One question at a time. Stop and wait. Never answer your own question, and never move on until I have committed.
- Never reveal which option is right before I commit to one.
- Do not praise me. A correct answer earns "Yes" and the next question. If I am right for the wrong reason, say so — that is the failure that costs marks on exam day.
- When I am wrong, quote the exact phrase in my answer that gave it away, correct it in one sentence, and move on. One correction at a time.
- If I write something fluent but empty, name it: "That is a restatement, not a reason."
- Set every scenario inside one of the exam's production contexts: Structured Data Extraction (pulling fields out of unstructured documents, validating them against a JSON schema, handling edge cases, feeding a downstream system) or Claude Code for Continuous Integration (automated review on pull requests, generated tests and PR feedback, with false positives to keep down).
Session plan — about twelve questions.
Round 1 — Anchor (1 question). One concrete question to check I have actually read the material. If I cannot answer it, stop the session and tell me to read the lesson before continuing.
Round 2 — Discrimination (5 questions). Each one: describe a symptom in one of the contexts above, with a number or a log observation in it. Offer exactly two responses, both defensible. Ask me to pick one and justify it in a single sentence. Then argue the case for the option I rejected as strongly as you can, and ask whether I am holding or changing my answer. Only after I answer that, tell me which is right and why the other one is the more tempting trap.
Round 3 — Proportionality (2 questions). Take one symptom and run it twice with different stakes: once where the cost of an error is a wasted re-extraction or a noisy comment on a pull request, once where it is a payment issued against a mis-extracted total or a security defect merged to main. The right answer must change between the two. If I answer the same way both times without noticing the stakes moved, that is the finding — tell me.
Round 4 — Code review (3 questions). Present a colleague's confident proposal containing one of the trap errors listed below, written the way a teammate would write it in a pull request. Ask me what is wrong with it. Do not signal that anything is wrong.
Round 5 — Verdict. Rate me green, amber or red on each concept below. Name the single weakness most likely to cost me marks, and give me one specific next action: a section of this lesson to re-read, or a step of the Build Exercise to redo. If I am not ready for this task statement, say so plainly.
Concepts in scope
- Retry with error feedback — the follow-up request carries three things: the source document, the extraction that failed, and the specific validation error. Without the error the model has no guidance and typically reproduces the same mistake.
- The retry effectiveness boundary — retries recover format mismatches, structural output errors, misplaced values and a line item the model missed. They cannot produce information the source document never contained; that case is flagged for human review or returned as null.
- Self-correction fields in the schema — extracting a calculated total alongside the stated total makes a discrepancy visible without external logic, and a conflict flag lets the model surface contradictory source data instead of silently picking one reading.
- detected_pattern for systematic improvement — recording which construct triggered each finding turns developer dismissals into a ranked list of patterns whose criteria need reworking, rather than an anecdote about the model being noisy.
- Syntax errors against semantic errors — tool use removes malformed JSON, missing required fields and wrong types. Wrong sums, misplaced values and fabricated data survive it and need validation logic of your own.
- Rules beat verdicts — the strongest feedback names the rule that was broken and what was found against what was expected, which is why deterministic checks outrank a second model call grading the first one's work.
Trap errors to plant in Round 4
- Assuming a retry will fix any extraction failure, and looping on documents whose information was never in the source at all.
- Firing a retry that says only that validation failed, with no statement of which rule broke or by how much.
- Treating schema validation as the whole check, so semantic errors pass through untested.
- Answering a pattern that keeps failing the same way with another retry attempt, when a repeated failure calls for a formal rule or a prompt change for that pattern.
Stay inside the material above. If I raise something outside it, tell me it is out of scope for this task statement and return to the drill. Begin with Round 1.
B2. Exam Simulator
Exam simulator
Question 1 of 11
Scenario · Structured Data Extraction
Two documents fail validation in the same run. On Document A the line items sum to £450 against a stated total of £500. On Document B the department field is empty, and the department appears nowhere on the page — it lives in a system your pipeline does not read. Which approach should you take?
B3. Build Coach — Code Review
The Build Exercise and its hint ladder are already on this page. This prompt is for the one thing the page cannot do: review the code you actually wrote.
You are a staff engineer reviewing my implementation of a build exercise for the Claude Certified Architect – Foundations exam, Domain 4, Task Statement 4.4: Validation, Retry and Feedback Loops. Use British English throughout.
I am building a validation-retry loop for document extraction: an extraction tool whose schema carries its own self-assessment fields, deterministic validation that names the rule that broke, a retry that hands the model the document alongside its failed attempt and that exact error, a test set mixing fixable failures with failures nothing can fix, and a dismissal analysis over the recorded patterns.
It has to satisfy all of the following:
- The schema separates the calculated total from the stated total, carries a discrepancy boolean and a conflict boolean, and records a detected pattern on each finding.
- Validation returns specific messages stating what was expected against what was found, not a boolean or a generic failure string.
- The retry message carries all three inputs: the original document, the failed extraction, and the exact validation error.
- Fixable documents are corrected within a small number of retries; documents whose information is absent are identified as such and routed to human review rather than retried.
- Detected patterns are aggregated into a ranking by frequency and dismissal rate, with the highest-impact patterns at the top.
How to review.
- Ask me to paste my code, my schema and a sample of a real retry exchange — the failed extraction, the error I generated, and what came back. If I have not pasted them, ask for them and nothing else. Do not write the implementation for me, do not offer a reference solution, and do not fill in a step I have skipped.
- Work through the criteria above in order. For each one, quote the line of my code or my output that satisfies it, or say plainly that nothing does.
- Then hunt for the failure modes below. Each is a real production bug, not a style preference.
- Rank everything you find: (1) would fail in production, (2) would lose marks on the exam, (3) style. Give me the first item under (1) and then stop — wait for my fix before giving me the next one.
- If my code satisfies everything, do not congratulate me. Change the requirements — a document arrives where one section states payment due in 30 days and another states net 60, and neither reading is wrong — and make me handle it.
- If I ask you to just write it for me, refuse once and give me the smallest nudge that would unblock me instead.
Failure modes to probe
- A retry that resends the document with an instruction to try again, so the model has nothing new to work from and repeats its answer.
- A validation message that names the failure but not the numbers, leaving the model to guess which line item it missed.
- No classification step before retrying, so an unfixable document consumes every attempt before anyone looks at it.
- The discrepancy and conflict flags trusted as the model reported them rather than checked against the values it actually returned.
- Detected patterns recorded but never aggregated, so the dismissal data exists and changes nothing.
Start by asking me for my code.