Implement validation, retry, and feedback loops for extraction quality
Learning objectives
Distinguish correctable output errors from unavailable information, construct useful retry feedback, and track review dismissals without treating every dismissal as a false positive. Preserve source conflicts instead of editing evidence to make validation pass.
Classify the failure before retrying
A failed extraction can arise at several layers. An invalid schema definition is a configuration problem. Malformed or nonconforming output is a structural problem. A correctly typed total that contradicts the line items is a semantic problem. A missing founding year may reflect genuinely absent information rather than a failed extraction.
Supported strict-output mechanisms reduce structural failures under their supported contracts, but do not correct an invalid schema or verify business meaning. Inspect completion status and actual errors. A retry-exhaustion status is a terminal failure of that attempt, not proof that the source contains the requested value.
| Situation | Appropriate next step |
|---|---|
| Invalid schema or unsupported feature | Repair configuration before another run |
| Present source value placed in the wrong field | Retry with source, failed output, and precise error |
| Required fact exists only in an unprovided external document | Obtain authorized evidence or record missing information |
| Source itself contains conflicting amounts | Preserve the conflict and route for resolution |
| Temporary read failure | Apply a bounded retry policy if the operation is safe to repeat |
A successful search with no matches, a denied search, and a failed connection are different outcomes. Do not convert all three to “No results found.” Likewise, an access failure does not prove that the source lacks the fact.
Construct a useful correction request
Retain the source identity and relevant original text, the failed extraction, and the validator's field-specific errors. Identify what may change and what must remain grounded in the source. Keep quoted source material separate from trusted workflow instructions.
For example, “Fix the JSON” does not tell the model whether the problem is syntax, a wrong field, or an unsupported value. “The source says 20 units; quantity contains the price 12. Move the source-supported quantity to quantity and recheck every field” gives a specific correction target.
If continuing a tool loop, preserve the assistant call and return results with the matching call IDs in the required protocol structure. Do not append an orphaned result or discard the context needed to interpret it. A correction is another candidate output and must pass validation again.
Bound the loop and preserve unresolved results
Set a maximum number of attempts and, where appropriate, a cost or elapsed-time limit. Count the initial attempt and retries explicitly. Stop on a terminal configuration error, unavailable evidence, or exhausted budget. Record the last usable partial data and the unresolved errors.
Retries can expose information that was present but previously overlooked. They cannot make an absent document become available. If the schema requires a non-null fact that the source never states, forcing repeated output generation encourages fabrication. Use the approved missingness representation or escalate the incompatible requirement.
Writer instructions and grader criteria must agree on the artifact, location, and contract. If one requires null for a missing value and the other forbids null, more iterations cannot resolve that contradiction honestly. Repair the contract first.
Worked example: a source-supported field repair
Assume the document INV-R7 states: “Quantity: 2. Unit price: USD 10.00. Stated total: USD 25.00. No tax, discount, shipping, or other adjustment.” All amounts are normalized to integer cents under this teaching contract.
The failed extraction is:
{
"document_id": "INV-R7",
"quantity": 1000,
"unit_price_cents": 2,
"stated_total_cents": 2500
}
The validator reports that quantity and unit price were exchanged relative to the source. It also requires a derived total and an explicit conflict indicator. The correction request includes the original text, the failed object, and those errors; it specifically forbids altering the stated source total to hide a mismatch. The complete expected corrective packet is {"source_id":"INV-R7","original_text":"Quantity: 2. Unit price: USD 10.00. Stated total: USD 25.00. No tax, discount, shipping, or other adjustment.","failed_extraction":{"document_id":"INV-R7","quantity":1000,"unit_price_cents":2,"stated_total_cents":2500},"validation_errors":[{"field":"quantity","observed":1000,"expected":2,"reason":"Source quantity is 2; price was placed in quantity."},{"field":"unit_price_cents","observed":2,"expected":1000,"reason":"Source USD10.00 equals 1000 integer cents."},{"field":"calculated_total_cents","observed":"missing","expected":2000,"reason":"Required independent calculation is 2*1000."},{"field":"conflict_detected","observed":"missing","expected":true,"reason":"Keep stated2500 separate from calculated2000."}],"instruction":"Return every declared field, preserve stated_total_cents=2500 and revalidate under the same source and no-adjustment rule. Do not claim payment or a completed API rerun."}.
The expected repaired candidate is:
{
"document_id": "INV-R7",
"quantity": 2,
"unit_price_cents": 1000,
"stated_total_cents": 2500,
"calculated_total_cents": 2000,
"conflict_detected": true
}
The arithmetic is 2 * 1000 = 2000, while the source states 2500. The candidate has repaired field placement and preserved a 500-cent source discrepancy. It is ready for a conflict-resolution workflow, not automatic payment. Rewriting the stated total to 2000 would make the numbers agree by falsifying the source.
The conflict rule depends on the explicit absence of adjustments. For an invoice that includes tax or shipping, validate the full component equation. If a component is missing, record that uncertainty instead of asserting the simpler equation applies.
Record patterns and dismissal reasons
For application-level review analytics, include a stable finding ID, detected_pattern, category, location, source revision, verification status, reviewer disposition, and disposition reason. A pattern such as unguarded-null-dereference is more specific than the broad category correctness.
Do not assume a product's reporting tool accepts a custom detected_pattern field. Use an application-owned record or map supported fields deliberately. A verdict describes the verification performed; an outcome such as fixed or skipped describes subsequent handling. Neither is a substitute for the pattern or the human's reason.
Consider this illustrative record:
{
"finding_id": "F17",
"detected_pattern": "unguarded-null-dereference",
"category": "correctness",
"revision": "R8",
"location": "src/parser.py:42",
"verification_status": "caller_not_yet_checked",
"disposition": "dismissed",
"disposition_reason": "Caller guarantees a non-null value; verify that invariant before labeling the finding false."
}
A dismissal can mean false positive, accepted risk, duplicate, out of scope, or an already-fixed issue. Adjudicate the reason against current code before labeling it. Count unique findings within a defined period and revision policy; distinguish a pattern's dismissed fraction from its measured false positive rate on labeled non-defects.
Improve the loop from observed evidence
Group adjudicated errors by construct, source layout, missingness state, and validator rule. Add targeted examples or repair tool descriptions for recurring mistakes. Retest on held-out cases, including acceptable patterns that should not trigger a finding. Keep the prompt, schema, rubric, and evaluation version together so comparisons remain meaningful.
A separate review pass can test the candidate against the source without relying on the writer's self-assessment. Inspect the saved artifact and actual check results. A model saying “fixed” while the arithmetic still disagrees is an unresolved failure. Confidence scores may guide investigation after calibration, but they cannot overrule a demonstrated contradiction.
Inspect the final result, not a success label
In the supplied SDK snapshot, a final result can report success, error_max_structured_output_retries, or another terminal subtype. Check the actual final structured_output field for presence, permitted type, schema and business checks, together with errors. success without a required payload is unusable here. If the declared schema allows 0 or false, those are present values, so a truthiness test is insufficient. Preserve parse/configuration/tool errors rather than hide them in an empty catch. A retry-exhaustion subtype can reflect repeated validation failure or a fallback retracting an earlier streamed payload without a valid replacement. Never reuse a retracted result as final success, and do not infer permanent impossibility from one subtype.
Keep three budgets separate: the application's writer/grader iterations, SDK structured-output retry attempts, and the whole agent's turns. The source's managed grading example describes max_iterations defaulting to 3; that is not a universal SDK retry default. Specify whether an application budget counts the initial attempt. A MAX_TURNS stop without the intended verification is incomplete; retain outputs and the concrete next step instead of raising the limit automatically. Repeated identical grader failures may indicate contradictory task/path/format/rubric requirements. A grader may itself be wrong; preserve previous failures and repair the actual contract before rerunning. The source gives a concrete contradiction: the writer is told “return JSON inline,” while the rubric reads a file under /mnt/session/outputs/. In a teaching case, the writer returns {"document_id":"COMP-1","founding_year":null} inline, but the grader reports “result.json missing” without examining that response. Preserve this failed attempt. If inline output was the intended contract, correct the rubric to inspect the actual inline object, its schema and exact source support, then perform a new check; do not silently change the task to file output merely to satisfy the mistaken grader. Increasing max_iterations does not repair this mismatch.
Expected application statuses might be {"status":"success_empty","query":"founding year","scope":"provided document A","results":[]}, {"status":"access_denied","scope":"external archive","error":"No permission","next_step":"Request authorized evidence"}, and {"status":"parse_failed","source":"document A","error":"Invalid response shape","next_step":"Repair parser/input"}. These example envelopes do not replace the actual tool's contract. Empty success, failed access, invalid input, transport failure and parse failure are distinct, and none proves the fact is absent everywhere.
For a missing-evidence stop, suppose local document COMP-1, section 2, names North Ltd but states no founding year. A failed candidate {"document_id":"COMP-1","founding_year":1999} fails “every non-null year must be supported by an exact source passage.” Under a teaching schema permitting null, the expected correction is {"document_id":"COMP-1","founding_year":null,"status":"missing_source_evidence"}. No same-input retry can justify 1999. If the intended schema forbids null, report the unsatisfied requirement and request adequate authorized evidence rather than weaken it silently. This example and INV-R7 are expected outputs, not records of an API rerun.
end_turn establishes turn completion, not extraction validity. A supported runner may automate call/result transport; manual code must execute only authorized actual requested calls, match every result/error to its real call ID, retain the assistant call and relevant source context, and apply the defined limits. First-text extraction, append/return fragments and a default “No analysis generated” string do not implement this full flow or prove the application goal passed.
Scope schema adapters and product examples
The local snapshot describes one Claude Code/MCP adapter flattening root combinators: allOf keeps requirements from every branch, while anyOf/oneOf branch required lists are described in prose. Merged properties and prose do not enforce every original alternative or exclusivity constraint. It reports root combinator tools skipped before v2.1.195 and unacceptable transformations logged/skipped. Inspect the actual transformed schema and server reason and preserve missing semantic checks; do not silently accept a weakened contract. Likewise, the snapshot's format annotation behavior and schema-startup errors are interface/version descriptions, requiring deployment validation, not universal JSON Schema semantics or zero-retry guarantees. More specifically, the local snapshot reports that before v2.1.205 invalid schemas were silently ignored with unstructured fallback and schemas containing format were treated as invalid; its later-described behavior accepts format as an annotation without enforcing it and reports invalid definitions at startup. Preserve that source-version split and inspect the actual deployment; none of these local claims is externally verified here.
The process_payment source fragment is an illustrative, interface-unspecified contract; its output_schema key and compilation claims must not be assumed supported everywhere. A teaching application could declare integer USD cents in (0,1000000], currency fixed to USD, and require transaction_id plus status only from an actual authorized transaction response. Missing, zero, negative, noninteger, over-limit or wrong-currency amounts are rejected before execution. A valid 2500 USD proposal is still not_executed until explicit payment authority and real execution evidence exist. A real failure stays failed. Defining a schema or extracting an invoice neither charges a card nor authorizes one. For this integer-cent teaching domain, expected pre-execution validation is [{"amount":null,"status":"reject_missing"},{"amount":0,"status":"reject_nonpositive"},{"amount":-1,"status":"reject_nonpositive"},{"amount":1,"status":"valid_not_executed"},{"amount":1000000,"status":"valid_not_executed"},{"amount":1000001,"status":"reject_over_limit"},{"amount":1.5,"status":"reject_noninteger"},{"amount":true,"status":"reject_boolean_type"},{"amount":"2500","status":"reject_string_type"}]; reject nonfinite numbers and malformed currency/amount formats rather than coerce them. These are expected domain checks, not transaction results. Complete currency/format fixtures under this USD-only policy are [{"input":{"amount":2500,"currency":"EUR"},"expected":{"status":"reject_currency","execution_status":"not_executed"}},{"input":{"amount":2500,"currency":null},"expected":{"status":"reject_currency","execution_status":"not_executed"}},{"input":{"amount":2500,"currency":"usd"},"expected":{"status":"reject_currency_format","execution_status":"not_executed"}},{"input":{"amount":"USD 25.00","currency":"USD"},"expected":{"status":"reject_amount_format","execution_status":"not_executed"}},{"input":{"amount":2500,"currency":"USD"},"expected":{"status":"valid_proposal","execution_status":"not_executed"}}]. No implicit unit conversion, case normalization or transaction is performed. The original illustrative input allows USD, EUR or GBP and its illustrative transaction response status is success or failed; the USD-only integer-cent application above deliberately narrows that teaching policy. Its valid_not_executed/rejection labels describe pre-execution application validation, not vendor transaction-response enum values.
Parse reports and verify findings with their actual evidence
Prefer the supported final structured response field and validate its actual schema and evidence afterward. This teaching application accepts only a final object with a required findings array; every nonempty entry must contain string file, summary and failure_scenario fields. This minimal application contract is separate from the full source-described ReportFindings envelope below. An empty array means a usable empty report under this schema, not proof that the reviewed code has no defects. A present null, false, number, array or text string fails this object schema; a missing field has its own missing-output diagnostic. Preserve the final subtype, errors and raw received value. Do not accept a previously retracted payload.
The application deliberately provides no text-fence fallback. Plain JSON text, exactly fenced JSON text, stray json words, missing closing fences and malformed JSON text are all text values, rejected as unsupported_text_payload without a split attempt. The source fragment checks for any json word before splitting an exact fence; an indexing/delimiter failure can escape its JSONDecodeError handler. That fragment is not a complete parser. The following complete received-value/expected-output pairs specify this application policy; they are expected fixtures, not an SDK run or a claim that this policy is universal:
[
{
"received": {},
"expected": {
"status": "missing_structured_output",
"report": null,
"error": "Final structured_output is absent."
}
},
{
"received": {
"structured_output": {
"findings": []
}
},
"expected": {
"status": "schema_valid_empty",
"report": {
"findings": []
},
"evidence_status": "not_adjudicated"
}
},
{
"received": {
"structured_output": {
"findings": [
{
"file": "src/parser.py",
"summary": "Possible null dereference.",
"failure_scenario": "A null caller argument reaches value.name."
}
]
}
},
"expected": {
"status": "schema_valid_requires_evidence_check",
"report": {
"findings": [
{
"file": "src/parser.py",
"summary": "Possible null dereference.",
"failure_scenario": "A null caller argument reaches value.name."
}
]
},
"evidence_status": "not_adjudicated"
}
},
{
"received": {
"structured_output": null
},
"expected": {
"status": "schema_failed",
"report": null,
"error": "Expected an object with a findings array."
}
},
{
"received": {
"structured_output": false
},
"expected": {
"status": "schema_failed",
"report": null,
"error": "Expected an object with a findings array."
}
},
{
"received": {
"structured_output": 0
},
"expected": {
"status": "schema_failed",
"report": null,
"error": "Expected an object with a findings array."
}
},
{
"received": {
"structured_output": []
},
"expected": {
"status": "schema_failed",
"report": null,
"error": "Expected an object with a findings array."
}
},
{
"received": {
"structured_output": {}
},
"expected": {
"status": "schema_failed",
"report": null,
"error": "Required findings field is absent."
}
},
{
"received": {
"structured_output": {
"findings": "none"
}
},
"expected": {
"status": "schema_failed",
"report": null,
"error": "findings must be an array."
}
},
{
"received": {
"structured_output": {
"findings": [
{
"file": "src/parser.py"
}
]
}
},
"expected": {
"status": "schema_failed",
"report": null,
"error": "findings[0] lacks string summary and failure_scenario fields."
}
},
{
"received": {
"structured_output": "{\"findings\":[]}"
},
"expected": {
"status": "unsupported_text_payload",
"report": null,
"error": "Text fallback is disabled; retain the raw value and request a supported structured result."
}
},
{
"received": {
"structured_output": "```json\n{\"findings\":[]}\n```"
},
"expected": {
"status": "unsupported_text_payload",
"report": null,
"error": "Text fallback is disabled; retain the raw value and request a supported structured result."
}
},
{
"received": {
"structured_output": "The word json is not a fence."
},
"expected": {
"status": "unsupported_text_payload",
"report": null,
"error": "Text fallback is disabled; retain the raw value and request a supported structured result."
}
},
{
"received": {
"structured_output": "```json\n{\"findings\":[]}"
},
"expected": {
"status": "unsupported_text_payload",
"report": null,
"error": "Text fallback is disabled; retain the raw value and request a supported structured result."
}
},
{
"received": {
"structured_output": "{\"findings\":"
},
"expected": {
"status": "unsupported_text_payload",
"report": null,
"error": "Text fallback is disabled; retain the raw value and request a supported structured result."
}
}
]
A schema-valid report still needs the actual revision, code and caller conditions checked before a finding can be confirmed. Empty reports, missing output, schema failures and transport/configuration errors retain distinct states. Retry only within the declared budget when the diagnosed cause can actually be corrected.
One source-described ReportFindings envelope contains a count, effort level, and severity-ordered findings. Each finding includes file, summary and failure_scenario; line is optional and 1-based. The snapshot describes base support at v2.1.196, category at v2.1.199, and short_summary at v2.1.212 with at most 60 characters; it gives a maximum of 32 findings per call and report effort levels low, medium, high, xhigh, max. Keep these local version guards qualified. Effort is not a per-finding severity. A verify-only verdict can be CONFIRMED or PLAUSIBLE and is absent on inline-only reviews; an outcome of fixed, skipped or no_change_needed describes the applicable later handling. PLAUSIBLE and not-fixed do not alone establish a false positive or a new failure. In this source, optional category is a short kebab-case slug. outcome is set only when re-reporting after the fix-application phase; it is not an arbitrary field on an initial report. An initial inline-only report omits verify-pass verdict and post-fix outcome when those phases did not occur.
For illustration, a one-finding report has count 1 and a finding at src/parser.py:42, summary “Possible dereference without a local null guard,” and failure scenario “If caller passes null, reading value.name fails.” Link its ID F17 and revision R8 to application pattern unguarded-null-dereference, code excerpt return value.name, run ID teaching-run-1, and caller-check evidence status pending. Do not set a verified verdict before that check. On later review, if an actual caller invariant rules out null, store the supporting caller location/excerpt and adjudication; a developer's unverified dismissal alone does not establish it. Custom pattern metadata belongs in an explicitly supported linked application record, not an assumed native field. The complete expected initial inline-only envelope is {"count":1,"level":"medium","findings":[{"file":"src/parser.py","line":42,"summary":"Possible dereference without a local null guard.","failure_scenario":"If caller passes null, reading value.name fails.","category":"correctness","short_summary":"Possible null dereference"}]}. The one-element array matches count1 and needs no multi-finding order; verdict/outcome are absent because no verification/fix phase was performed. F17/R8/pattern/code/run metadata remain in the linked application record rather than unsupported native fields.
For a fixed teaching population of 10 unique findings in one revision/period, four dismissed findings give a dismissal share of 40%. If later adjudication finds three of the ten findings are real defects and seven are nondefects, precision is 3/10=30% for these positive findings. A false-positive rate additionally needs the assessed nondefect population: if an independent test set contains 20 nondefects and seven trigger findings, FPR is 7/20=35%, not 4/10. Keep populations distinct and unadjudicated cases unknown. Under the same definitions, zero posted findings gives {"posted_findings":0,"dismissed_findings":0,"true_positive_findings":0,"dismissal_share":null,"precision":null,"status":"undefined_zero_posted_findings"}. A test set containing no assessed nondefects gives {"assessed_nondefects":0,"false_positive_findings_on_nondefects":0,"false_positive_rate":null,"status":"undefined_zero_nondefects"}. Neither undefined rate is a measured zero; missing adjudication remains unknown separately from a known zero denominator. Pattern associations do not prove a prompt or construct caused an error; evaluate changed criteria on relevant held-out cases before claiming improvement.
Find/triage/report separation requires the real finding, current code revision, rubric and supported artifacts. Enforce actual tool/path/side-effect scope; names such as Read/Grep/Glob and denying Bash alone do not prove a universal readonly sandbox. Mixed stateless/client query fragments are conceptual unless a complete supported caller is established. A separate role does not prove it was invoked or finished.
Check all arithmetic states and source limits
For INV-R7, compare exact integer cents with no tolerance under the stated no-adjustment rule. The existing mismatch output is correct. If an otherwise identical source states USD 20.00, the complete expected result is {"document_id":"INV-R7-match","quantity":2,"unit_price_cents":1000,"stated_total_cents":2000,"calculated_total_cents":2000,"conflict_detected":false,"validation_status":"agreement_under_rule"}. If unit price is unreadable, use {"document_id":"INV-R7-unknown","quantity":2,"unit_price_cents":null,"stated_total_cents":2500,"calculated_total_cents":null,"conflict_detected":null,"validation_status":"unassessable_missing_price"} under an explicitly nullable teaching schema. Invalid quantities, incomplete components or mixed currencies also remain unassessable until a valid policy/input exists. Never default uncertainty to conflict_detected:false.
Preserve each conflicting value's actual document/page/section, version and relevant date. Freshness and reliability are judgment inputs; two copies of one source are not independent corroboration, and confidence scores cannot override contradictions. For PDF input, verify actual relevant readable page/chunk identity and cross-page conditions. Ordering PDFs before text, upright legible pages, standard fonts, chunking and caching are source/interface-specific suggestions. Page-specific feedback can target a real omission; caching neither supplies missing attachments nor makes illegible content correct. Record absent/unreadable evidence honestly.
The supplied material is a local compiled snapshot. The original files named by its citation anchors were not supplied for this audit and have not been read or externally verified here. Glossary descriptions and registry metadata do not independently establish product behavior. The source's false-completion anecdotes motivate comparing actual artifacts, builds and logs with claims. They do not establish a universal motive or guarantee prevention through a grader. State exactly what was checked and what remains expected, failed, unperformed or unknown.
Read the source sketches and diagnostic signals precisely
Inspect actual tool-call counts, repeated requests, parameter-validation errors and response contents. The supplied diagnostic suggests that redundant calls can indicate unsuitable pagination or token-limit parameters, while repeated invalid-parameter errors can call for clearer tool-description examples. These are hypotheses to test against the real call/error evidence, not proof of a cause or permission to change an unsupported setting. A corrected parameter or retrieval path may justify a bounded retry; unchanged successful calls returning absent or irrelevant evidence do not create the missing fact.
The local result-handling sketch labeled Python is actually TypeScript: it imports query, declares const objects and uses for await. Its truthiness test and empty catch still have the presence/diagnostic limits described above. Reconstructing indentation or changing a language label does not turn it into a verified robust implementation.
The original illustrative payment definition uses input_schema with required amount and currency: amount is merely a number without declared units or bounds. It uses the interface-unspecified output_schema with required string transaction_id and status, the latter limited to success or failed. The displayed definition omits strict; the following source advice mentions strict: true. Neither that advice nor the printed keys establishes supported placement, compilation or execution in an actual API. Use the deployed interface contract and the explicitly narrowed USD-cent teaching policy above without inventing transaction evidence.
The source regex searches a <reasoning> text tag; it does not independently calculate a total, validate invoice items or establish a conflict. This lesson instead computes the declared integer-cent equation and compares the supported fields explicitly. Extracting private intermediate reasoning is unnecessary for this validation.
Summary
Retry only when the next attempt has a plausible correction path. Supply the failed candidate and exact errors, preserve genuine missingness and source conflicts, and validate again. Track specific patterns and adjudicated reasons so feedback improves the system rather than merely changing its wording.
