By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A scanned invoice for 1,317.60 USD reaches your pipeline. The extractor returns JSON, the loader accepts it, and the ledger posts the invoice as 0.00. Two weeks later the vendor calls about an unpaid bill.
The object had every required key. The total_cents field held the string '1,317.60', and the loader wrote null. A schema would have caught that in milliseconds. Nobody ran one.
This lab is scenario 6 from the six published CCAR-F scenarios: structured data extraction. Your brief: define a JSON Schema for an invoice, reject any object that fails it, feed the errors back for one retry, and send the document to human review when the retries run out.
JSON Schema is a JSON document that describes the shape another JSON document must have. It can require fields, fix types, list allowed values and match patterns. It cannot add numbers together.
| Check | Schema or code? | Why |
|---|---|---|
total_cents is an integer | Schema | A type check |
currency is USD, EUR or GBP | Schema | An enum |
issue_date looks like 2026-03-14 | Schema | A pattern |
issue_date is a real date | Code | 2026-02-30 matches the pattern |
Line items sum to subtotal_cents | Code | Arithmetic |
Subtotal plus tax equals total_cents | Code | Arithmetic |
The split matters on the exam and in production. A field can pass its schema and still be wrong in the world. Run both layers, and report both kinds of error in the same list.
Amounts stay integers in cents. A float total is a second bug waiting behind the first, because 0.1 + 0.2 is not 0.3 in binary floating point. Count in cents and convert once, at the edge of the system.
Do not confuse a prompt instruction with a validator. Asking the model for valid JSON is a request; the schema check is the enforcement. Keep both, and trust only the second.
Validation sits between the model and the ledger. The ledger only ever sees objects that passed both layers, and a rejected object never leaves a partial record behind.
The schema uses a small subset of JSON Schema: type, required, enum, pattern, minLength, minimum, items, minItems and additionalProperties.
A production pipeline would use the jsonschema package. This lab writes the checks by hand so you can see what the package does, and so it runs on the standard library alone.
Every error names the path where a check failed, in the form $.line_items[1].quantity. That path is what the retry feeds back to the model, so the next attempt knows where to look.
"""Lab 2: schema-validated invoice extraction with a retry loop."""
from __future__ import annotations
import json
import re
from datetime import date
INVOICE_SCHEMA = {
"type": "object",
"additionalProperties": False,
"required": [
"invoice_number",
"vendor",
"currency",
"issue_date",
"line_items",
"subtotal_cents",
"tax_cents",
"total_cents",
],
"properties": {
"invoice_number": {"type": "string", "pattern": r"^INV-\d{4}$"},
"vendor": {"type": "string", "minLength": 1},
"currency": {"type": "string", "enum": ["USD", "EUR", "GBP"]},
"issue_date": {"type": "string", "pattern": r"^\d{4}-\d{2}-\d{2}$"},
"line_items": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": False,
"required": ["description", "quantity", "unit_price_cents"],
"properties": {
"description": {"type": "string", "minLength": 1},
"quantity": {"type": "integer", "minimum": 1},
"unit_price_cents": {"type": "integer", "minimum": 0},
},
},
},
"subtotal_cents": {"type": "integer", "minimum": 0},
"tax_cents": {"type": "integer", "minimum": 0},
"total_cents": {"type": "integer", "minimum": 0},
},
}
TYPES = {
"object": dict,
"array": list,
"string": str,
"integer": int,
"number": (int, float),
}
def validate(value, schema, path="$"):
"""Check the JSON Schema keywords this pipeline relies on."""
errors = []
expected = schema.get("type")
if expected is None:
return errors
if not isinstance(value, TYPES[expected]):
return [f"{path}: expected {expected}, got {type(value).__name__}"]
if expected == "object":
for key in schema.get("required", []):
if key not in value:
errors.append(f"{path}: missing required field '{key}'")
if schema.get("additionalProperties") is False:
for key in sorted(set(value) - set(schema["properties"])):
errors.append(f"{path}: unexpected field '{key}'")
for key, child in value.items():
if key in schema["properties"]:
errors.extend(validate(child, schema["properties"][key], f"{path}.{key}"))
elif expected == "array":
if len(value) < schema.get("minItems", 0):
errors.append(f"{path}: needs at least {schema['minItems']} item(s)")
for index, child in enumerate(value):
errors.extend(validate(child, schema.get("items", {}), f"{path}[{index}]"))
elif expected == "string":
if "enum" in schema and value not in schema["enum"]:
errors.append(f"{path}: {value!r} is not one of {schema['enum']}")
if "pattern" in schema and not re.search(schema["pattern"], value):
errors.append(f"{path}: {value!r} does not match {schema['pattern']}")
if len(value) < schema.get("minLength", 0):
errors.append(f"{path}: needs at least {schema['minLength']} character(s)")
elif expected in ("integer", "number"):
if "minimum" in schema and value < schema["minimum"]:
errors.append(f"{path}: {value} is below the minimum {schema['minimum']}")
return errors
def check_business_rules(invoice):
"""Rules JSON Schema cannot express: real dates and arithmetic."""
errors = []
issue_date = invoice.get("issue_date")
if isinstance(issue_date, str) and re.fullmatch(r"\d{4}-\d{2}-\d{2}", issue_date):
try:
date.fromisoformat(issue_date)
except ValueError:
errors.append(f"$.issue_date: {issue_date!r} is not a real date")
items = invoice.get("line_items") or []
priced = [
item
for item in items
if isinstance(item.get("quantity"), int)
and isinstance(item.get("unit_price_cents"), int)
]
subtotal = invoice.get("subtotal_cents")
if len(priced) == len(items) and isinstance(subtotal, int):
line_total = sum(i["quantity"] * i["unit_price_cents"] for i in priced)
if line_total != subtotal:
errors.append(
f"$.subtotal_cents: line items sum to {line_total}, not {subtotal}"
)
amounts = [invoice.get("subtotal_cents"), invoice.get("tax_cents"), invoice.get("total_cents")]
if all(isinstance(amount, int) for amount in amounts):
if amounts[0] + amounts[1] != amounts[2]:
errors.append("$.total_cents: subtotal plus tax does not equal the total")
return errors
def validate_invoice(invoice):
return validate(invoice, INVOICE_SCHEMA) + check_business_rules(invoice)The retry loop is short on purpose. Extract, validate, and on failure pass the error list as feedback. Stop after two attempts.
Two details make it safe. The pipeline never guesses a value to fill a gap, and the fallback is a review item, not an empty record. A missing invoice is a queue entry; a wrong invoice is a payment.
The scripted extractor returns canned attempts, so the run is deterministic and needs no API key.
class FakeExtractor:
"""Returns one scripted extraction per attempt; ignores document and feedback."""
def __init__(self, attempts):
self._attempts = list(attempts)
self._index = 0
def extract(self, document, feedback):
attempt = self._attempts[self._index]
self._index += 1
return attempt
def extract_invoice(document, extractor, max_attempts=2):
attempts = []
feedback = None
for number in range(1, max_attempts + 1):
invoice = extractor.extract(document, feedback)
errors = validate_invoice(invoice)
attempts.append(
{"attempt": number, "invoice": invoice, "errors": errors, "feedback": feedback}
)
if not errors:
return {"status": "accepted", "invoice": invoice, "attempts": attempts}
feedback = errors
return {
"status": "human_review",
"invoice": None,
"review": {"queue": "invoice-review", "errors": attempts[-1]["errors"]},
"attempts": attempts,
}
GOOD_INVOICE = {
"invoice_number": "INV-2041",
"vendor": "Northwind Supply",
"currency": "USD",
"issue_date": "2026-03-14",
"line_items": [
{"description": "Steel shelf", "quantity": 2, "unit_price_cents": 42000},
{"description": "Assembly kit", "quantity": 1, "unit_price_cents": 38000},
],
"subtotal_cents": 122000,
"tax_cents": 9760,
"total_cents": 131760,
}
BAD_ATTEMPT = dict(
GOOD_INVOICE,
issue_date="03/14/2026",
currency="usd",
subtotal_cents=121000,
total_cents=130760,
)
BROKEN_INVOICE = dict(
GOOD_INVOICE,
invoice_number="77",
issue_date="2026-02-30",
subtotal_cents=98000,
tax_cents=0,
total_cents=98000,
line_items=[{"description": "Freight pallet", "quantity": 1, "unit_price_cents": 98000}],
)
STILL_BROKEN_INVOICE = dict(BROKEN_INVOICE, invoice_number="INV-0077", total_cents=90000)
def show(label, result):
print(label)
for attempt in result["attempts"]:
verdict = "accepted" if not attempt["errors"] else f"rejected ({len(attempt['errors'])})"
print(f" attempt {attempt['attempt']} {verdict}")
if attempt["feedback"]:
print(f" feedback sent: {len(attempt['feedback'])} error(s)")
for error in attempt["errors"]:
print(f" - {error}")
if not attempt["errors"]:
print(" " + json.dumps(attempt["invoice"], sort_keys=True, separators=(",", ":")))
print(f" status: {result['status']}")
if result["status"] == "human_review":
review = result["review"]
print(f" review queue: {review['queue']} errors attached: {len(review['errors'])}")
print()
def main():
show(
"CASE 1 one bad attempt, then a corrected extraction",
extract_invoice("Northwind Supply INV-2041", FakeExtractor([BAD_ATTEMPT, GOOD_INVOICE])),
)
show(
"CASE 2 both attempts rejected, hand to a person",
extract_invoice("Bluepeak Freight scan", FakeExtractor([BROKEN_INVOICE, STILL_BROKEN_INVOICE])),
)
if __name__ == "__main__":
main()Save both parts as lab2_invoices.py and run it with Python 3.11 or newer. No packages, no key.
python lab2_invoices.pyCase 1 shows the loop working. Attempt 1 fails three checks, and those three errors go back as feedback. Attempt 2 fixes all three, and the arithmetic passes: two shelves at 420.00 USD plus a 380.00 USD kit is 1,220.00 USD, tax 97.60 USD, total 1,317.60 USD.
Case 2 shows the loop refusing to invent. Attempt 1 has an invoice number of 77 and a date of February 30. Attempt 2 fixes the number and breaks the total instead. Two different attempts, one result: human review, with both error lists attached.
Track three numbers once this runs in production: first-attempt acceptance, acceptance after the retry, and review rate. A retry rate that climbs after a prompt change is a regression, even when every invoice still posts.
Extraction pipelines fail quietly, because valid JSON feels like correct data. Each of these four failures needs a control.
| Failure | What you see | Control |
|---|---|---|
| A plausible but wrong total | Valid JSON and a wrong ledger entry | Arithmetic checks, then review on any mismatch |
| The retry repeats the same error | Two identical failures and a wasted call | Cap the attempts; stop early when the error list does not change |
| The fallback writes a partial record | A null total reaches the ledger anyway | The review item carries both attempts and every error; nothing is accepted |
| The schema allows extra fields | An unexpected field slips downstream | additionalProperties: false on every object |
Your pipeline is done when every line below is true. Re-run the verification command after each change.
2026-02-30 is rejected even though it matches the date pattern.human_review and the queue is invoice-review.accepted status appears only after the schema and the arithmetic both pass.The stretch task has three parts. Each one hardens a different part of the pipeline.
invoice_number values and reject a second invoice with the same number. Decide whether that belongs in the schema or in the business rules, and say why.Key takeaways
A schema fixes shape, not truth; arithmetic and real dates need code.
Name the failing path in every error so the retry has something to act on.
Feed the error list back once, then stop and hand the document to a person.
The fallback returns a review item with evidence, never a half-filled invoice.
additionalProperties: false is the cheapest way to stop silent field creep.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.