All chapters
  1. Start hereParseable is not valid. Valid is not correct
  2. Foundations · 1From free text to fields and records: why contracts matter
  3. Foundations · 2Syntax, schema, semantics, business validity: four different kinds of right
  4. Foundations · 3JSON and JSON Schema: types, enums, nullable fields, unions and nested objects
  5. Building · 4Typed models: Pydantic in Python, records and Bean Validation in Java
  6. Building · 5Provider output modes: prompting, JSON mode, constrained decoding and tool arguments
  7. Building · 6Tool input, tool result, agent handoff, final response: four contracts on one path
  8. Building · 7Schema design: names, required or optional, and where each value came from
  9. Operating · 8Validation stages: parse, schema, cross-field, domain rules
  10. Operating · 9Errors and repair: retry, clarify, correct within bounds, fall back
  11. Operating · 10Schema evolution: versions, compatibility and migrations
  12. Operating · 11Security: a valid string can still be an attack
  13. Operating · 12Observing contracts: validation failures, schema drift and replay artifacts
  14. Operating · 13Testing contracts: golden examples, property-based tests, fuzzing and contract suites
  15. Reference · 14Frameworks and standards: what each one checks for you
  16. Reference · 15Advanced: partial objects in a stream, polymorphism, multilingual data and typed events
  17. Reference · 16The insurance lab: one submission, four contracts, end to end
  18. ReferenceGlossary
  19. AboutAbout this site and its sources
Building · 4

Typed models: Pydantic in Python, records and Bean Validation in Java

A schema describes data. A typed model lets code hold it. The same recommendation as a Pydantic model and as a Java record, and where the two treat the same payload differently.

What you will understand
Schema and model
A schema describes data; a typed model is the object your code holds after the data was checked.
Coercion
Why "0.62" becomes 0.62, and "yes" becomes true, without anyone being told.
Two stacks, one payload
Pydantic and a Java record read the same 22 texts and disagree on 6 of them in their default setup.
Strict, on purpose
The settings that make each stack refuse instead of convert, and what strict still lets through.

Here is the recommendation of the underwriting agent for the shared case UW-004, as one payload of a recorded test run. Read it to the end:

{
  "recommendation": "escalate",
  "reasons": [
    "Roof age on the application (9 years) and from the provider (22 years) differ by more than 5 years."
  ],
  "citations": ["R-ROOF-03"],
  "missing": [],
  "stated_confidence": 0.62,
  "requires_human": true,
  "policy_version": "2026.2",
  "recommendation": "approve"
}

The key recommendation appears twice. The first value is the right one: the application says 9 years, the roof-data provider says 22, and rule R-ROOF-03 of the policy fixture (the illustrative rule set of the example) sends that case to a senior underwriter. The last line says approve.

A Pydantic model, a widely used Python library for typed data, read this text in its default mode and in its strict mode. Both times it accepted the payload and stored "recommendation": "approve". No error, no warning. A Java record read by Jackson, the common Java JSON library, rejected it in both of its setups. Same text, same contract, opposite results. The model recommends; a person decides, and here the person would be handed an approve that the agent's own reasons contradict.

This page is about the step after the schema: turning checked JSON into an object your code can hold, and the quiet decisions each library makes while doing it.

A typed model: the object your code holds#

Plain English. A typed model is a class whose fields have declared types, built from data, so the rest of the program works with rec.stated_confidence as a number instead of data["stated_confidence"] as whatever the JSON held. For example: a Recommendation class with a field stated_confidence: float. Once an object of that class exists, every later line of code may assume the field is a number.

The JSON Schema page described the shape. A schema is data about data: it can be sent to a provider, stored next to the contract, checked by any language. A typed model is code: it lives in one language and gives that language's compiler, editor and tests something to hold. Most production systems want both, and the question this page answers is how they meet.

The smallest version is in the example itself. examples/uw-contracts/contracts.py defines the recommendation as a standard-library dataclass. Its rule, stated in the module docstring, is that the class is built only from a value that has already passed the validation stages, and that from_dict() "does not convert or guess: a wrong type raises". This is the start of the class, quoted from the file:

@dataclass(frozen=True)
class Recommendation:
    """Version 1, written by the model. A recommendation to the underwriter, never a decision."""
    recommendation: Decision
    reasons: list[str]
    citations: list[str]
    missing: list[str]
    stated_confidence: float
    requires_human: bool
    policy_version: str
    evidence_ids: list[str] = field(default_factory=list)   # version 2 only

Two choices in it matter. frozen=True makes the object unchangeable after it is built, so no later step can quietly edit a value the validator approved. And Decision is a Literal of the four words, so a type checker flags code that compares with "approved".

Before AI. A Spring controller with @Valid @RequestBody Recommendation rec does the same three things: Jackson reads the request body into a Java object, Bean Validation checks its annotations, and the method receives a typed value or the framework returns a 400. Nothing on this page is new to a Java team. What is new is the producer. A browser form or a partner service is code someone wrote and tested against your API. A model writes the text fresh every time, so the corners of the reader's behaviour (what it converts, what it ignores, which duplicate wins) get exercised far more often.

The same recommendation in Python and in Java#

The twins folder, examples/uw-contracts/twins/, holds the same contract twice. Both versions were run once, outside this repository, on 2026-11-17, and the site replays the recording. The versions are fixed by its README: Python 3.14.7 with Pydantic 2.14.3 (pydantic-core 2.50.4); Java 23.0.1 compiled for release 17, Jackson jackson-databind 2.23.0, Jakarta Validation API 3.1.1 and Hibernate Validator 9.1.6.Final. If a version changes, the results may change.

Pydantic is a library. A model is a class that inherits from BaseModel; field types and constraints are declared with type hints and Field(...). This is twins/python/models.py, verbatim:

class Recommendation(BaseModel):
    recommendation: Literal["approve", "decline", "request_info", "escalate"]
    reasons: list[str] = Field(min_length=1)
    citations: list[RuleId]
    missing: list[str]
    stated_confidence: float = Field(ge=0.0, le=1.0)
    requires_human: bool
    policy_version: str = Field(pattern=r"^\d{4}\.\d+$")

    # requires_human is typed bool, not Literal[True], on purpose:
    # the type check ("is this a boolean?") and the business rule
    # ("it must be true", R-HUMAN-01) then report as two different errors.
    @field_validator("requires_human")
    @classmethod
    def a_person_decides(cls, value: bool) -> bool:
        if value is not True:
            raise ValueError("requires_human must be true (R-HUMAN-01)")
        return value


class StrictRecommendation(Recommendation):
    model_config = ConfigDict(strict=True, extra="forbid")

A Java record is a language feature; the Record class documentation marks it "Since: 16". The Java documentation calls a record class "a shallowly immutable, transparent carrier for a fixed set of values, called the record components"; the compiler provides the constructor, the accessors, equals, hashCode and toString. On its own a record checks nothing. Two more parts do the work. Jackson (a library) maps JSON to the record: that step is called JSON mapping. Bean Validation, standardized as Jakarta Validation (a standard; Hibernate Validator is the implementation that ran), checks constraint annotations on the object Jackson built. This is twins/java/src/main/java/twins/Recommendation.java without its comment:

@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public record Recommendation(
        @NotNull Decision recommendation,
        @NotEmpty List<@NotBlank String> reasons,
        @NotNull List<@Pattern(regexp = "R-[A-Z]+-\\d{2}") String> citations,
        @NotNull List<@NotBlank String> missing,
        @DecimalMin("0.0") @DecimalMax("1.0") double statedConfidence,
        @NotNull @AssertTrue Boolean requiresHuman,
        @NotNull @Pattern(regexp = "\\d{4}\\.\\d+") String policyVersion) {
}

Two components differ on purpose, and the README says so. statedConfidence is the primitive double, which cannot hold null. requiresHuman is the boxed Boolean, which can, so it carries @NotNull next to @AssertTrue. The Jakarta Validation specification says of @AssertTrue: "null elements are considered valid". Without @NotNull, a null would pass the rule that a person must decide.

The diagram puts the three readers of this page side by side: the example's standard-library path, Pydantic, and the Java pair.

Diagram: Three readers of one payload · where the converting and the checking happen

Each lane is one way to turn the recommendation text into a typed object. Read left to right. Pydantic does everything in one call. The Java pair has two steps, and Bean Validation never runs if Jackson stopped. The example's own path refuses before it builds anything, and converts nothing.

  1. This example
    1. strictjson: A strict parser: a duplicate key is a syntax error.
    2. minischema: A string where a number belongs is an error, never a number.
    3. Later stages: Checks that need the whole record or the facts of the run, in validate.py.
    4. Recommendation.from_dict: Built only from a value that passed; a wrong type raises instead of converting.
  2. Pydantic
    1. Parse: In the run, a duplicate key was accepted and the last value kept, in both modes.
    2. Coerce or refuse: Default mode converts "0.62" and "yes"; strict mode refuses them.
    3. Field constraints: Bounds, patterns, the R-HUMAN-01 validator; every error in one list.
    4. Model instance: A BaseModel object, or one exception holding all errors.
  3. Java record
    1. Jackson reads: The ObjectMapper maps keys to record components and throws at the first mismatch.
    2. Coerce or refuse: Default features convert scalars and turn null into 0.0 for a double; the strict mapper sets nine features.
    3. Bean Validation: Checks annotations such as NotNull, DecimalMin and DecimalMax on the object Jackson built.
    4. Record: A Java record with no violations.

The important difference is the number of steps. Pydantic parses, converts and checks constraints in one call and returns one list of errors. The Java path has two steps: Jackson stops at the first problem it meets while reading, and Bean Validation runs only if reading succeeded. The example's own path has three, and converts nothing at all.

Coercion: the reader changes the value to fit#

Plain English. Coercion means the reader converts a value to the type it expected instead of rejecting it. The JSON says "stated_confidence": "0.62", a string; the field wants a number; the reader turns the string into 0.62 and carries on. Nothing in the stored object shows that the producer sent a string.

Both libraries coerce by default, and both document it. The Pydantic strict-mode page says: "By default, Pydantic will attempt to coerce values to the desired type when possible." Its conversion table lists, for a bool field in default (lax) mode, string inputs that are "Case-insensitive. Allowed values: '0', 'off', 'f', 'false', 'n', 'no', '1', 'on', 't', 'true', 'y', 'yes'". Jackson's mapper feature ALLOW_COERCION_OF_SCALARS is listed on its wiki with "(default: true)".

Coercion was designed for a real problem. Query strings and form posts carry everything as text, and a web framework that rejected ?page=2 because "2" is a string would be useless. For a model's output the trade is different. A model that writes "0.62" where the contract says number has not followed the contract, and the evidence of that disappears inside the reader. If the same model starts writing "yes" for requires_human, a lax reader keeps working while the producer drifts away from the contract.

Strict mode is the opposite setting: no conversion, and no unknown fields. In Pydantic, strict mode is set for a model with ConfigDict(strict=True), and unknown fields are a separate setting: extra "Defaults to 'ignore'", and 'forbid' raises a ValidationError. In Jackson 2 there is no single switch; the strict mapper of the twins sets nine features, each named in Mappers.java.

Common confusion. Strict is not "no conversion at all". The Pydantic conversion table allows an int input for a float field in strict mode, for Python and JSON input. In the run, both strict readers accepted the JSON integer 1 for stated_confidence and stored 1.0. That is harmless here, and it is still a conversion.

Try it: 22 payloads, four readers#

The lab replays the recorded run. Pick one of the 22 variants of the UW-004 recommendation and see what each of the four readers did: accepted, accepted with a changed value, or rejected, with the stored value and the errors. The values are synthetic, and the recording is of real library code, not of a model; no model was called.

The summary of the recorded run, copied from twins/README.md (generated there from recorded/results.json). "accepted (changed)" means the reader accepted the payload and the stored value differs from the text that was sent.

PayloadPydantic defaultPydantic strictJava, default mapperJava, strict mapper
valid_baseacceptedacceptedacceptedaccepted
confidence_as_stringaccepted (changed)rejectedaccepted (changed)rejected
confidence_integeracceptedacceptedacceptedaccepted
number_in_string_listrejectedrejectedaccepted (changed)rejected
bool_as_string_trueaccepted (changed)rejectedaccepted (changed)rejected
bool_as_oneaccepted (changed)rejectedaccepted (changed)rejected
bool_as_yesaccepted (changed)rejectedrejectedrejected
requires_human_falserejectedrejectedrejectedrejected
enum_near_missrejectedrejectedrejectedrejected
enum_wrong_caserejectedrejectedrejectedrejected
missing_policy_versionrejectedrejectedrejectedrejected
null_policy_versionrejectedrejectedrejectedrejected
null_requires_humanrejectedrejectedrejectedrejected
null_confidencerejectedrejectedaccepted (changed)rejected
unknown_extra_fieldaccepted (changed)rejectedrejectedrejected
reasons_single_stringrejectedrejectedrejectedrejected
reasons_emptyrejectedrejectedrejectedrejected
confidence_out_of_rangerejectedrejectedrejectedrejected
policy_version_as_numberrejectedrejectedaccepted (changed)rejected
duplicate_keyaccepted (changed)accepted (changed)rejectedrejected
citation_bad_patternrejectedrejectedrejectedrejected
trailing_commarejectedrejectedrejectedrejected

Read the two default columns against each other first. They agree on 16 rows and differ on 6: number_in_string_list, bool_as_yes, null_confidence, unknown_extra_field, policy_version_as_number and duplicate_key. Then read the two strict columns: they differ on one row only, the duplicate key. Strict settings bring the stacks much closer together. They do not make them identical.

Where the two stacks treat one payload differently#

The twins README lists the most instructive differences. Five of them change what reaches the underwriter cockpit.

They convert different things. Both defaults turned "0.62" into 0.62, and "true" and 1 into true. Only Pydantic accepted "yes" as true; default Jackson rejected it with "only "true" or "false" recognized". Only Jackson turned a number into a string: 7 in the missing list became "7", and 2026.2 became the string "2026.2". Pydantic rejected both, even in default mode, which matches its conversion table: a str field accepts a number "Only if coerce_numbers_to_str is enabled".

A null became 0.0 with no error. With the default Jackson mapper, "stated_confidence": null was accepted as 0.0 for the primitive double, inside the allowed range, so Bean Validation had nothing to object to. The documented default explains it: FAIL_ON_NULL_FOR_PRIMITIVES is "(default: false)" on the Jackson wiki. Pydantic rejected the null in both modes, and the strict mapper rejected it. The diagram below follows that one value.

Diagram: One null, three readers · how "no confidence given" became "zero confidence"

The payload says stated_confidence null. Pydantic and the strict Java mapper reject it. The default Java mapper turns it into 0.0 for a primitive double; 0.0 is inside the allowed range, so Bean Validation passes it, and the cockpit sorts the case to the bottom.

  1. The payload
    1. stated_confidence: null: The model said nothing about its confidence.
  2. Reading
    1. Pydantic, both modes: A float field does not accept null.
    2. Strict mapper: FAIL_ON_NULL_FOR_PRIMITIVES is on.
    3. Default mapper: FAIL_ON_NULL_FOR_PRIMITIVES is off by default in Jackson 2, so null becomes the primitive's default.
  3. Constraints
    1. DecimalMin 0.0, DecimalMax 1.0: 0.0 is inside the range, so Bean Validation has nothing to object to.
  4. What the cockpit sees
    1. Confidence 0.0: A model that gave no confidence is stored as one that gave none at all, and sorted last.

The trap is not the number. It is that a model saying nothing about its confidence is stored as a model saying it has none, and a cockpit that sorts its queue by stated confidence puts the case at the bottom. The safe forms are a boxed Double with @NotNull, or the strict mapper. The README names the boxed form; the recorded run does not show it.

The unknown field: the two defaults are opposite. Default Pydantic ignored premium_usd and dropped it, as its extra default of 'ignore' says. Default Jackson 2 rejected it, because FAIL_ON_UNKNOWN_PROPERTIES is enabled by default. Strict Pydantic rejected it only because the model also sets extra="forbid"; strict mode alone is about types.

The duplicate key passed Pydantic in both modes. The last value won, which is how the opening payload became approve. Jackson's strict mapper rejected it with STRICT_DUPLICATE_DETECTION. The default mapper rejected it too, but by a side effect of the record ("No fallback setter/field defined for creator property"), not through a duplicate check; the README records this as observed in the run, not documented. RFC 8259 says object names "SHOULD be unique" and that with duplicates "the behavior of software that receives such an object is unpredictable" (four layers quotes it). The run shows what unpredictable means in practice.

Absent and null are told apart in Pydantic, not on the default Java path. Pydantic reported missing for the absent policy_version and string_type for the null. With the default mapper both arrived as null and both produced the same @NotNull message. The strict mapper told them apart again, with two different features (FAIL_ON_MISSING_CREATOR_PROPERTIES and FAIL_ON_NULL_CREATOR_PROPERTIES). The JSON Schema page explained why the difference matters: a repair message for "you left it out" is not the one for "you wrote null".

Production pitfall. Jackson 3 changes three of these defaults. Its release notes say FAIL_ON_UNKNOWN_PROPERTIES changes to false, and FAIL_ON_NULL_FOR_PRIMITIVES and FAIL_ON_TRAILING_TOKENS change to true. So the java_default outcomes of unknown_extra_field and null_confidence are specific to Jackson 2. Jackson 3 was not run here. An upgrade of a JSON library can flip what your contract accepts without a line of your code changing; pin the configuration, not only the version.

The example's own path: refuse first, then build the object#

The example does not use either library. Its order is the one the validation page teaches: parse with a strict parser, validate against the schema, and only then build the dataclass. The demonstration runs five of the twins payloads through that path. It proves that this path rejects each of the five that a default reader accepted or changed, and reports why. It does not prove the path is better in general: it converts nothing, so it would also reject inputs a lax reader is right to accept in other systems.

import json
from strictjson import loads, ParseError
from minischema import validate
from validate import load_schema
from contracts import Recommendation

schema = load_schema("recommendation.v1")
payloads = {p["id"]: p["text"] for p in json.load(open("twins/payloads.json"))["payloads"]}

for pid in ["confidence_as_string", "bool_as_one", "null_confidence", "unknown_extra_field", "duplicate_key"]:
    try:
        value = loads(payloads[pid])                      # parse: strict, no duplicate keys
    except ParseError as e:
        print(f"{pid:<22} parse   {e}")
        continue
    errors = validate(value, schema)                     # schema: no conversion at all
    if errors:
        print(f"{pid:<22} schema  {errors[0]['path']} {errors[0]['message']}")
        continue
    rec = Recommendation.from_dict(value)                # typed model, built only after both checks
    print(f"{pid:<22} typed   {rec.recommendation} {rec.stated_confidence}")

Output of a real run in a scratch copy of examples/uw-contracts (no model is called; the payloads are fixed texts):

confidence_as_string   schema  /stated_confidence expected number, got string
bool_as_one            schema  /requires_human expected boolean, got integer
null_confidence        schema  /stated_confidence expected number, got null
unknown_extra_field    schema  /premium_usd property "premium_usd" is not allowed
duplicate_key          parse   duplicate key "recommendation" at position 294

The duplicate key never reaches the schema. The parser of the example (strictjson.py) treats it as a syntax error, because its docstring gives the reason: Python's own json.loads "keeps the LAST value of a duplicate key without a word". That is the same behaviour the recorded Pydantic run showed. The lesson is about order: whichever library holds your typed model, the decision about duplicates, nulls and conversions happens in the reading step, before any constraint runs.

In our insurance agent. The workflow keeps one JSON Schema per contract as the source of truth and builds typed objects only from values that passed it. In a Python service the typed model would be a Pydantic class in strict mode with extra="forbid", behind a parser that rejects duplicate keys. In a Java service it would be a record read by a strict mapper, with boxed types and @NotNull wherever null must be refused.
What this is not. This page compares how two stacks read one payload. Profiles of each library and standard (Pydantic, Jackson, Hibernate Validator, Zod, Ajv) live on frameworks. The runtime that calls the model and hands its output to this code is the harness, at harness.sammuthu.com.
For a coding agent. The same choice exists in CI. A pipeline that reads a coding agent's change_report with a lax reader accepts "needs_review": "no" as false in a library that coerces strings to booleans, and merges without review. Read it strictly, and let a type error stop the pipeline. Review and CI lanes live on diff-to-deploy.sammuthu.com.

What each library documents#

These rows are from each project's own documentation, read today; the fact log has the URLs. Pydantic and Jackson are libraries, Jakarta Validation is a standard, and Hibernate Validator is its implementation.

BehaviourPydantic (2.x docs)Jackson 2 (wiki)Jakarta Validation 3.1
Converts scalar types by defaultyes: "will attempt to coerce values to the desired type when possible"yes: ALLOW_COERCION_OF_SCALARS default truenot its job: it checks an object that already exists
Unknown keys by defaultignored: extra defaults to 'ignore'rejected: FAIL_ON_UNKNOWN_PROPERTIES default truecannot see JSON keys
null for a primitive numbernot on the pages read; rejected in the run (float_type)becomes the default: FAIL_ON_NULL_FOR_PRIMITIVES default false@NotNull is the constraint that rejects null
How to turn strictness onConfigDict(strict=True), Field(strict=True) or strict=True per call; extra="forbid"one feature per behaviour; nine in the twinsn/a
Schema from the modelmodel_json_schema(), documented as compliant with JSON Schema 2020-12 and OpenAPI 3.1.0not covered on the pages readnot covered

The last row matters for the next page. A Pydantic model can produce a JSON Schema, so one Python class can be both the typed model and the schema you send to a model provider. That is convenient, and it hides a gap: the generated schema describes types and constraints, but a custom validator such as a_person_decides is Python code, and the documentation read here does not say it appears in the generated schema. The rule R-HUMAN-01 would be enforced by your reader and invisible to the provider.

Which is the source of truth: the schema or the model?Three designs, and what each one makes easy to break

Schema first: the JSON Schema is the contract, and typed models in each language are generated from it or hand-written and tested against it. Every language gets the same rules; generated code can be awkward, and rules that are not schema keywords (cross-field and domain checks) live in code anyway.

Model first: a Pydantic class (or a Java record with annotations) is the contract, and the schema is exported from it. One file, one language, good editor support. The exported schema may miss what the code checks in custom validators, and a second language must trust an export it cannot read back into its own types without loss.

Both, with a test: keep the schema as the contract, keep the typed model as a convenience, and run the golden examples of testing through both, so a difference fails CI. The example does a form of this: assets/schema-core.js and the Python validator are checked against one table of expected results by scripts/test_schema_core.mjs.

Where a lax reader is the right choiceStrict at untrusted producers, tolerant between your own services

Strict reading is right where the producer is a model or an outside provider: every conversion hides a deviation you want to see and count. Between two services you deploy, a tolerant reader that ignores unknown fields is often right, because it lets the producer add a field before every consumer is updated. That is the evolution argument, and it is about unknown fields, not about type conversion. Converting "0.62" to 0.62 is rarely what any contract wants; ignoring an unknown field often is. Keep the two settings separate in your head, as Pydantic keeps strict and extra separate.

Error shapes differ tooNames, paths and how many errors you get back

Pydantic reported errors with a location such as missing.0 and a type such as string_type, all in one list. Jackson raised one exception, such as MismatchedInputException, at the first problem, naming the JSON key (stated_confidence) because of the snake-case naming strategy. Bean Validation named the record component (statedConfidence). A workflow that turns library errors into the error record of the validation page (stage, JSON Pointer path, code, message) needs one small adapter per library, and a test that each adapter produces the same path for the same payload. Without it, a failure dashboard counts missing.0, missing[0] and /missing/0 as three different fields.

Bounds on a doubleA specification that says one thing and an implementation that does another

The Jakarta Validation specification says, for @DecimalMin and @DecimalMax, that "double and float are not supported due to rounding errors (some providers might provide some approximative support)". Hibernate Validator 9.1.6.Final did check the double in the run and reported 1.2 as out of range. That is the "approximative support" the sentence allows, not a guarantee of the standard. Where an exact boundary matters (a limit of 25 years in a rule, a percentage that must not exceed 100), use BigDecimal or an integer unit, and test the boundary value itself.

Checklist#

In one breath#

A schema describes the data; a typed model is the object your code holds once the data has been checked. The reading step that builds it is where libraries make quiet choices: converting "0.62" to a number, "yes" to true, null to 0.0, keeping the last of two duplicate keys or ignoring a field nobody asked for. Pydantic and Jackson make different quiet choices on the same payload, so read a model's output strictly, reject duplicates in the parser, and test the configuration you depend on.

The workflow can now hold a recommendation as a typed object and knows which payloads its readers would have bent. All of that happens after the model has written its text. Model providers offer modes that shape the text while it is written, from a request in the prompt to decoding that cannot leave a grammar. Provider modes shows what each of them guarantees, and which of the failures on this page and the last two they leave in place.