Repository navigation
fix(json-schema): read model keys on nullable objects, check $defs entries, flag model keys no class reads - #407
Conversation
…s bodies A `["object", "null"]` node is rewritten to `anyOf` before parsing, and its model-scope keys stayed beside the `anyOf` instead of on the object arm that becomes the class. The node built `DynamicModel` at match_threshold 0.7, so a near-miss `items` element at 0.9 against a declared 0.93 counted tp 1 instead of fd 1 / fp 1. The object arm now carries `x-aws-stickler-model-name`, `-match-threshold` and `-infer-unspecified`. Regression from 0.7.0. The extension walk entered `$defs` / `definitions` bodies with no scope, so a typo there imported silently while the same typo inline raised. Definitions are now checked and read only model-scope keys. A field-scope key inside one raises and points at the property that uses the definition, beside its `$ref`, where it is already read; honouring it would make the key work on a property `$ref` and vanish on an `items` `$ref`. Both are breaking: results move for nullable-object schemas that declared a model key, and schemas with a typo or field key inside a definition now raise. Refs #349 (part A only; B and C are out of scope) Closes #340
A scalar, array, combiner or alias definition generates no class, so the "definition" scope accepted model keys there and then dropped them. Such a definition now reads neither set. The field-key error names the $ref, and a non-mapping $defs is walked as before. Docs and CHANGELOG narrowed to where definition keys are actually read; the CHANGELOG notes invalid values on an ["object","null"] node now raise. Refs #340, #349.
Security Scan ResultsASH Security Scan Report
Scan Metadata
SummaryScanner ResultsThe table below shows findings by scanner, with status based on severity thresholds and dependencies:
Report generated by Automated Security Helper (ASH) at 2026-11-18T18:30:25+00:00 |
vawsgit
left a comment
There was a problem hiding this comment.
needs changes
["object","null"] model keys and pydantic model_json_schema() output work as described. Three blockers:
json_schema_importer.py:189. The new "definition" scope accepts model keys on every$defsobject, but they are silently dropped when the definition is reached throughallOfor a root$ref. A declaredmatch-threshold: 0.93builds at 0.7 with no error. #407 (comment)json_schema_importer.py:183. A definition used fromitemsraises "belongs on the property beside its$ref". Moving the key there then raises "is not read on objecta[]". The author has no working position for the key. #407 (comment)README.md:246anddocs/docs/Advanced/dynamic-models.md:113. The new docs present["object","null"]as reading the same keys as"object", but at the root that shape raisesAttributeError: model_fields. The crash predates this PR, but the docs should not advertise the shape as supported until it is fixed. #407 (comment)
Optional: the mapping-definition gap (r4296905610) and the duplicated branch (r4296906064).
…sition Addresses review on #407. - Model keys on an `allOf` arm (inline or through `$ref`), or on a definition reached through `allOf` or a root `$ref`, now raise. They passed the check and were dropped: a definition's match-threshold 0.93 built `AllOfModel` / `DynamicModel` at 0.7. The root `$ref` message points beside the `$ref`, where the root reads them. - A field key inside a definition now names both working positions: beside the `$ref`, or on the array property when used as `items`. - A `$defs` body is a "definition" only when it has `properties`. A `type: "object"` mapping becomes a `dict` field and reads no model keys. - A union root (`["object", "null"]`, root `anyOf`/`oneOf`) raises a clear ValueError instead of `AttributeError: model_fields`. Docs now limit the list-form statement to nested nodes. - Fold the duplicated "model"/"definition" branches. Refs #340, #349.
|
Thanks for the careful review, @vawsgit. All five are addressed in c54d83b, and I merged current dev in.
22 new tests. Full suite: 3013 passed. Ready for another look. |
| body, | ||
| f"{path}.{key}.{name}" if path else f"{key}.{name}", | ||
| "definition" | ||
| if isinstance(body, dict) and "properties" in body |
There was a problem hiding this comment.
Non-blocking — suggest a follow-on issue.
A type: "object" definition is classified differently from the same node inline.
The definition walk treats a body as an object definition only when "properties" in body. The inline walk uses _is_object_schema, which also counts type: "object" and ["object", "null"]. The same node therefore gives two different results:
properties.m: {"type": "object", "additionalProperties": {...}, "x-aws-stickler-match-threshold": 0.9}is accepted (scopefield_or_model).$defs.Mwith the same body raises... belongs on the object definition with 'properties'.
The PR description also says an object definition is type: "object", ["object", "null"], or properties, which the code does not match. One rule should apply in both places. Either call _is_object_schema(body) here, or, if a mapping really reads no model keys (as the comment says), tighten _is_object_schema so the inline case also raises.
There was a problem hiding this comment.
This is still tracked as #463, item 1, and this PR does not change the classification. The docs no longer suggest it does: dynamic-models.md now says object-level keys also raise "at three positions where no class reads them", which leaves an inline type: "object" mapping out (8d5460e). Leaving this open until #463 is scheduled.
| elif key == "items": | ||
| visit(value, f"{path}[]" if path else "[]") | ||
| else: | ||
| visit(value, f"{path}.{key}" if path else key) |
There was a problem hiding this comment.
Non-blocking — suggest a follow-on issue.
visit walks non-schema values and unreachable definitions. Optional; this is not a blocker for the allOf regression.
The fallback visit(value, ...) descends into every key except the four data keywords and _PRESERVED_EXAMPLES_KEY. That includes x-aws-stickler-comparator-config and x-comparison payloads. A comparator config dict that contains an allOf list of dicts with an x-aws-stickler-model-name key would raise as if it were a schema. visit also checks allOf arms inside $defs entries that no $ref reaches, so an unused definition can make the import fail. Skip x-* keys, as walk does through its scope handling.
There was a problem hiding this comment.
Fixed in 4c5bcf0. Data keywords (default, examples) and x-* payloads are no longer walked as schemas, and an unreached definition is not walked.
There was a problem hiding this comment.
A correction to my earlier reply. The x-* half holds. An x-* payload is walked only where a $ref points into it, since that subtree then builds part of the model (5eb442c), and only the node the $ref points at is walked, for its contents. A $ref held by an unused definition reaches its target too, as on dev, so a typo inside an x-* node that only an unused definition references raises (bedee34). A typo on the referenced node itself raises too, as on dev, when it is a property or items node (a9c1d22). A member of the payload named like a keyword, such as anyOf or definitions, is read as a schema there, as on dev, so a typo on #/x-models/anyOf/properties/p raises and a field key on a property named items under it is read (526ecef). A typo in another member of the same payload imports, since no $ref reaches it. A $ref held in another unreached payload or in a data value is not followed, so a payload that only such a $ref names is not checked. The CHANGELOG lists what moves from raising to importing in an unreached payload: a typo, a misplaced key, patternProperties, or a keyword beside a combiner (b1cbdcf, 8d5460e, 330c7ac). TestValuesAreNotWalkedAsSchemas pins the skip (bac75cf, 55e064b). With the skip removed, 14 tests fail at d581b21, including test_a_comparator_config_shaped_like_a_schema_imports, which uses a config holding properties with x-aws-stickler-thresold, or patternProperties. Your exact case, an allOf of model keys inside a comparator config, imports either way: walked as a schema it builds nothing, and model keys are valid on an arm. So on its own it does not pin the skip.
The unreached-definition half no longer holds. 933b682 walks a $defs entry that no $ref reaches for its contents again, as dev does. Skipping it let a typo in an unused definition's property import where dev raises. So an unused definition can still fail the import, as on dev: one whose allOf arm carries x-aws-stickler-weight raises. Only the entry's own keys go unchecked, which the dereferenced schema on the line-1070 thread needs. I kept that half as dev has it. Happy to take it to a follow-up if you want unused definitions skipped entirely.
vawsgit
left a comment
There was a problem hiding this comment.
needs changes
All three earlier blockers are fixed on c54d83b, and both optional items are done. One blocker remains:
json_schema_importer.py:1065._reject_unread_model_keysraises when anyallOfarm reaches a keyed definition, even when another property$refs the same definition and reads its keys. A schema withhome: {$ref Addr}andwork: {allOf: [{$ref Addr}]}buildsAddressat 0.93 ondev. On this head the whole import raises. Either skip the error when the definition's keys are read through another path, or keep the check and fix item 2. #407 (comment)CHANGELOG.md:90. The entry says a schema that now raises "loses no working configuration". The case in item 1 makes that untrue. #407 (comment)
The other 5 inline comments are non-blocking and are suggestions for follow-on issues.
vawsgit
left a comment
There was a problem hiding this comment.
needs changes
Measured on head c54d83b and on dev 4f4f4b5. Merged with dev, the full suite passes (3,903 passed). Two blockers make from_json_schema() raise on schemas that import and score correctly on dev (inline):
json_schema_importer.py:1065TheallOfblocker from the 2026-10-20 review is still open, and it fires on more shapes than reported. The suggested fix (skip the error when another path reads the keys) does not cover the case of an unused$defsentry.json_schema_importer.py:970Every$defsentry is now validated, referenced or not, so dereferenced schemas raise.
Both make CHANGELOG.md:90 ("loses no working configuration") false.
Two medium issues are pre-existing on dev, but they contradict this PR's stated behaviour (inline): json_schema_importer.py:903 (the null arm) and json_schema_importer.py:1003 (keys beside a $ref in items are dropped silently).
…ys nothing reads Every $defs entry was validated, referenced or not, so a dereferenced schema (refs inlined, $defs kept) raised for keys that its inlined copies read. Model keys on an allOf arm raised even when another position built the same object from them, or when the allOf built nothing (an unused definition, under 'not'). A definition is now walked once a $ref reaches it. The allOf and root $ref checks run after the walk, only for positions that build a class, and skip any object some other position reads. Data keywords and x-* payloads are no longer walked as schemas. The second traversal in _reject_unread_model_keys is folded into the walk.
`["object", "null"]` beside a `$ref` is rewritten to anyOf, and every
non-type keyword, the `$ref` included, was copied onto each arm. The null
arm then parsed as a second object, so the node built a union of two
classes compared with ExactComparator: a one-character difference scored
0.0 where `"object"` scored 0.9.
The null arm is now `{"type": "null"}`, and the object arm drops its
`type` beside a `$ref`, which otherwise made the parser merge the two
into a new class. Pre-existing on dev.
…s before" A root `$ref` to a nullable property failed on dev with an AttributeError and fails here with the root-shape ValueError, so "fails as it did" overstated it. The import builds what dev builds and warns, or still fails and does not warn.
…ort-holes # Conflicts: # CHANGELOG.md
_resolve_local_ref marked any segment after `$defs` or `definitions` as a definition entry, even when that segment was a property NAMED like the keyword. So `#/properties/definitions/properties/term` queued `properties.definitions.properties` as an entry and walked its property map as a schema: a sub-property named `items`, `anyOf` or `patternProperties` then raised, where dev imports. Read the pointer from the root, as _is_property_pointer does, and mark an entry only where the segment before was read as the keyword.
The walk skips x-* payloads, and a $ref target is walked from the reference for its contents only, so a typo or misplaced key on a property or items node under an x-* key (`#/x-models/T/properties/p`, `#/$defs/W/x-sub/properties/p`, `#/x-models/L/items`) imported where dev raised. Check that node's own keys from the reference, with the path and scope the walk would give it there. The path and the x-* test read the pointer as the walk does, so a property NAMED `properties` keeps its name in the label and a property NAMED `x-a` is not an x-* key. A root $ref to a non-object property under x-models now raises dev's "belongs on the object" error, so the two tests that matched the root-$ref message now match that one.
…he warned import drops the keys A $ref into an x-* payload walks the node it points at for its contents, plus a property or items node's own keys, not the rest of the payload: a typo in another member imports. Say so in the CHANGELOG and dynamic-models.md, where they said the payload, or whatever the $refs point to, is checked. The warned import is not always what dev built: beside a $ref, ["object", "null"] builds Optional[Row] with the default comparator, where dev built Union[Row, Row, None] with ExactComparator. The Changed entry and the unread() docstring now say only that the keys are dropped.
… keyword of a schema Three places decided on their own whether a key named $defs or definitions held definitions, and each read too much: - _resolve_local_ref kept a second reading under a key no schema keyword holds, so `#/components/schemas/G/properties/definitions/ properties/q/items`, or `#/x-models/G/$defs/X`, resolved into a definition entry and checked it as one. - collect() took any such key inside an x-* payload or a data value (examples, default, enum, const) as a set of definitions and walked its entries as schemas. - The walk sent a member named so of a map no schema keyword holds (`components.schemas.definitions`) to the definitions queue. Each raised where dev imports. One rule now decides in all three: _position_after reads each key as what it is in the document, and only a $defs or definitions keyword of a schema (the root, or a node reached from it through schema keywords) holds definitions. A property name, a member of another map, and anything inside an x-* payload or a data keyword do not. The resolver and the walk both use it, and collect() is gone, since nothing inside a value holds definitions. So a $defs inside default or an x-* payload is no longer walked: a typo in its entries imports, and a $ref it holds is not followed. The three tests that pinned the old walk now assert the import. A test pins that an unused entry named `properties` is checked as an entry.
State the rule the importer now applies: only a $defs or definitions keyword of the root, or of a node reached from it through schema keywords, holds entries. One under components, inside an x-* payload or a data value, or a property named so, holds none. The CHANGELOG said a $defs entry inside an x-* payload or a data value was still walked for its contents; it no longer is.
…ntry The entry said an unused definition's contents are checked "as before". Dev walked the $defs mapping as a schema, so an entry named like a keyword was read as that keyword: a typo in a property of an entry named `properties` imported, and an entry named `items`, `anyOf`, `allOf` or `patternProperties` had its own keys checked, or its name rejected. This branch reads each as an entry, so the first now raises and the rest import. Say so. Measured on dev 6f76236 and this branch.
_validate_supported_shapes walks every $ref target, an unused entry's
too. Where the target is a map of schemas by name, such as
`#/properties` or `#/$defs/W/properties`, it walked the map as a schema,
so a property named like a keyword was read as that keyword. Dev, which
never followed a $ref, only walked such a map by name. Each of these
raised where dev imports:
- a property named `oneOf` beside another, or one named
`patternProperties`, under `{"$ref": "#/properties"}`;
- a field key on a property named `items`, `definitions`, `$defs`,
`anyOf`, `oneOf` or `allOf` of a used `W`, with an unused
`{"$ref": "#/$defs/W/properties"}` beside it. A class reads the key
there, and dropping the alias imported it.
The same held under `#/x-models/...`, `#/components/...` and a data
value. Such a target is now walked one member at a time, reading each
segment as the walk around it does. Its members' contents are still
checked.
…aves unresolved The parser leaves a $ref back into a type it is still building as a name, the pointer's last segment. Where no model has that name (an array definition, `#/properties/kind`), the field's type stays undefined, and reading its schema raised PydanticUserError. Named `type`, it resolved to the builtin and raised PydanticInvalidForJsonSchema. Dev built a list form beside such a $ref (`["object", "null"]`) as a union of two classes, so it imported. Building one class, as "object" does, made it raise the pydantic error too, where dev imported. Every form now raises the ValueError for a recursive model, naming the field.
…ray or where object fails With the null arm no longer a copy of the $ref, a list form beside one builds what the single type builds, and dev did not: - Where "object" fails to import, the list form now fails too: a comparator on an array whose items are `["object", "null"]` beside a $ref, or on an anyOf whose arm is such a $ref to an array of objects, and a $ref to an array of objects with no properties. Dev built a union of two classes there, which imported. - `["array", "null"]` beside a $ref builds what "array" does: an array of objects at field threshold 0.5, or the target's class with LevenshteinComparator at 0.7. Dev built a union compared with ExactComparator at 1.0. - `["object", "array", "null"]` still builds a union, of two arms where dev built three. The "object" cases pass on dev. The rest fail there.
…le type builds The CHANGELOG documented the null-arm fix for `["object", "null"]` only. It also applies to `["array", "null"]` beside a $ref, which now builds what "array" does: an array of objects at field threshold 0.5, or a $ref to an object as that class with LevenshteinComparator at 0.7, where dev built a union compared with ExactComparator at 1.0. `["object", "array", "null"]` still builds a union, of two arms. Where the single type fails to import, the list form now fails too, where dev's union imported. Say which shapes, add an entry for the recursive $ref that now raises the recursion ValueError, and say that a $ref to a properties map reads it by name. dynamic-models.md states the list-form rule in one sentence.
…in a $ref target
walk_target decided whether a $ref target is a map of schemas by name
with _is_named_map, which read every segment as a keyword wherever the
walk reads a node as a schema. So a member named `definitions`, `$defs`
or `dependentSchemas` under `components`, an `x-*` payload or a data
value was read as that keyword, and a $ref to it walked its
`properties` map as a schema. A property named `items`, `anyOf`,
`allOf` or `patternProperties` there was then read as that keyword, and
the import raised where dev imports and reads the key:
- `{"$ref": "#/components/schemas/definitions"}` from a property,
`items` or the root, with a property `items` at threshold 0.9 or
`anyOf` at weight 2.0, or properties `allOf` and `b`, or
`patternProperties`;
- the same under `#/x-models/...`, `#/$defs/W/x-sub/...` and
`#/properties/a/default/...`;
- `not: {"$ref": "#/components/schemas/definitions/properties"}`.
_is_named_map now reads those keywords as a map only as a keyword of a
schema, as _position_after does. A `properties` key of any node the walk
reads as a schema is still one. All 112 new cases fail on the previous
head and pass on dev 6f76236.
…a holds it _is_named_map and _walk_position each read the segments of a $ref pointer their own way, and both read keyword names as keywords at positions that are no schema: - a member named `anyOf`, `oneOf`, `allOf` or `prefixItems` of an `x-*` payload or `#/components/schemas` was read as a list, so the next segment was taken for an index, and a property named `properties` two segments on was read as the keyword. A $ref to `#/x-models/anyOf/properties/properties` raised that threshold 0.9 on its property `items` is not read, where dev reads it; a property named `anyOf` or `patternProperties` there raised a shape error; and a typo on `#/x-models/anyOf/properties/p` imported, where dev raises. - _walk_position read `definitions`, `$defs` and `dependentSchemas` as maps under an `x-*` payload, so `#/x-models/definitions/properties/ items` was checked as an `items` node and raised for a field key. Both now read the pointer with one helper, _map_holders: a key is a keyword only where the node holding it is read as a schema. A `properties` key of any such node holds names, as the walk reads it. The other map keywords hold names only as a keyword of a schema reached from the root through schema keywords, as _position_after reads them. A pointer passes only through objects, so a list keyword before another segment holds an object, read as a schema. _is_property_pointer also counts a property in this reading. TestAKeywordIsReadOnlyWhereASchemaHoldsIt: 63 cases, all pass on dev c70ca6e; 54 fail on the previous head.
…ked, as dev did
Reading a `$defs` or `definitions` entry named `properties` as an entry,
not as the `properties` keyword of its set of definitions, also checked
the entry's own shape, which dev never did: dev read the entry as a map
of properties and checked each member instead. So `patternProperties`,
or `anyOf` beside `properties`, at the top of such an entry raised
("Unsupported anyOf for field '$defs.properties'") where dev imports,
whether a `$ref` reaches the entry or not.
walk gains a `shapes` flag, off for such an entry only. Its keys and
contents are still checked as an entry's, so a typo in one of its
properties still raises, as the CHANGELOG says.
test_an_entry_named_properties_keeps_its_own_shape_unchecked: 6 cases,
pass on dev c70ca6e, fail on f58142e. (The previous commit's message
says 54 of its 63 cases fail on f58142e; the count is 44.)
… to one builds on dev
The null arm of a list-form `type` beside a $ref became `{"type":
"null"}`, so that `["object", "null"]` beside a $ref to an object builds
one class rather than a union of two. Beside a $ref to a scalar, dev's
null arm kept the $ref, so every arm parsed as that scalar, and the node
built what the single type builds. Dropping the $ref there made the
field nullable:
- `items: {"$ref": "#/$defs/S", "type": ["array", "null"]}`, with `S` a
string, built `list[Optional[str]]`, where dev and `"array"` build
`list[str]`;
- a required property typed `["object", "null"]` beside a $ref to a
number built `Optional[float]`, where dev and `"object"` build `float`.
The null arm keeps the $ref again where the end of the $ref chain is a
scalar: only scalar types declared, or none with `enum` or `const`, and
no keyword that builds an object, an array or a union.
28 new cases in TestAListFormTypeBesideARef, for both orders of both
list forms, a string, number and enum target, directly and through an
alias. All pass on dev c70ca6e and fail on f58142e.
… on dev - `"type": ["object"]` is rewritten like `["object", "null"]`, so it now reads the model keys too (`Row` at 0.9, where dev built `DynamicModel` at 0.7). The CHANGELOG, dynamic-models.md and the evaluator README named only `["object", "null"]`. - Beside a $ref to a scalar, a nullable list form builds that scalar, as on dev, so a required property stays required. - The shape of a definition entry named `properties` is still not checked, as on dev; only its keys and contents are. - A member of an `x-*` payload or other value named like a keyword is a schema, so a $ref through it reads the `properties` under it as names.
|
thanks for this. the one thing to look at before 1.0.2. on would you be open to keeping the 1.0.2 PR to the |
vawsgit
left a comment
There was a problem hiding this comment.
✅ LGTM!
I measured head d581b21 against dev c70ca6e and against the head merged into dev (the merge has no conflicts). Every run printed stickler.__file__ to confirm which tree it imported.
All three findings from my 2026-10-30 review are fixed:
- The
allOfcheck missed readers in$reftargets outside$defs: fixed. Every resolved$reftarget is now queued with the reading position'sbuiltflag (). I ran thestickler/src/stickler/structured_object_evaluator/models/json_schema_importer.py
Lines 1411 to 1413 in d581b21
#/components/Personschema on both trees. On dev and on head,team.leadbuildsPersonat 0.93, andemployee(allOf) buildsAllOfModelat 0.7. Thex-modelsvariant also matches dev. Removing that queue branch makes 26 tests fail. CHANGELOG.mdsaid "loses no working configuration": fixed. The sentence is gone. The replacement claim, "Every key that now raises was dropped in silence" (), held in a differential fuzz of about 18,500 generated schemas run on dev and head. In 2,051 of them, dev imports and head raises. In none of those 2,051 did dev read a key that head now rejects.Lines 135 to 138 in d581b21
- The "beside its
$ref" advice failed for a union arm: fixed. The error now names theanyOf/oneOf/allOf. Following the advice works:anyOfwith a threshold gives 0.9, andallOfwith a weight gives 2.0. A scalar definition is not offeredallOf, because a one-armallOfof a scalar fails on dev too.
I also ran a script for each claim in the 2026-11-18 inline replies, and every claim held.
What else I checked:
- Full suite with the
devandllmextras: 5197 passed, 11 skipped, 1 xfailed, on head and on the merged tree.ruff check .is clean. The docs and README example tests give 88 passed. - The importer test files grow from 70 tests to 706, as the PR body says. All 29 rows of the "Before and after" table reproduce on dev and head.
- Mutation testing: 21 of 22 mutations of the importer were caught, with 4 to 123 tests failing each. The mutation no test caught removes the
if fields:gate on the warnings, and it changes no tested behavior. A sharper mutation that issues the warnings right after validation makes 6 tests fail. - Against base, the PR changes only the importer, its two test files,
CHANGELOG.md,dynamic-models.mdand the README. CI, the version floors and dead code are unchanged.
Non-blocking (low):
- : the warnings are still issued when the import then fails while creating the model. The PR body says "An import that fails anyway gives no warning", but that holds only for failures before field conversion. Repro:
pis{"type":"object","$ref":"#/$defs/Row","x-aws-stickler-match-threshold":0.93}, androwsis{"type":"array","items":{"$ref":"#/$defs/Row"},"x-aws-stickler-comparator":"ExactComparator"}. The import warns aboutp, then raisesList[StructuredModel] ... cannot have a 'comparator'. - : model keys on a definition that has both
stickler/src/stickler/structured_object_evaluator/models/json_schema_importer.py
Lines 1598 to 1600 in d581b21
$refandpropertiesare still dropped silently, as on dev. The definition gets scope"definition"and accepts the keys, then builds the$reftarget (Rowat 0.7).
|
Thanks Diego, good catch on the scope. You're right that my 3 Nov comment on #340 said these would be warnings in 1.0.x. I've changed course deliberately: #407 ships the new errors in 1.0.2. The rule I'm applying is the one proposed in #587: input the docs never allowed, such as a misspelled Where the docs did accept a key (a model key beside a If the team disagrees with that line, #587 is the place to settle it, and I'll follow whatever we agree for 1.1.0. |
Closes #340.
Refs #349 (part A; parts B and C are not addressed).
Root causes
#349 A.
_prepare_schemarewrites"type": ["object", "null"]toanyOfbefore parsing. Thex-aws-stickler-*keys stayed beside theanyOf, and the arms were built without them, so the class was built asDynamicModelat0.7while its field keys were honoured.0.7.0read the name and threshold, so this is a 1.0.0 regression. Beside a$ref, the rewrite also copied the$refonto the null arm, so the node became a union of two classes compared withExactComparator.#340.
_validate_supported_shapesentered each$defs/definitionsbody with no scope, so a definition's own keys were never checked. A typo there imported silently where the same typo inline raised, andx-aws-stickler-threshold: 0.88inside a definition resolved the default with no warning.The change
All in
models/json_schema_importer.py. Validation is one walk over the schema, plus a queue of$reftargets that the same walk drains.List-form object type. The object arm gets the model-scope keys, for
["object", "null"]and["object"]alike. Beside a$ref, the null arm is{"type": "null"}, so["object", "null"]builds one class with the field's comparator, as"object"does.["array", "null"]beside a$refto an object builds what"array"builds, and a shape where"object"fails to import beside the same$reffails the same way for the list form. Beside a$refto a scalar, the null arm keeps the$ref, as on dev, so every arm builds the scalar and a required property stays required.A definition a
$refreaches is checked under its own scope. Withpropertiesit accepts only the model-scope keys, plusx-aws-stickler-aggregate, which is accepted and ignored as on a field. Any other definition (scalar, array, combiner, alias, mapping) generates no class and accepts neither set. A$refto a node inside an entry checks the entry and walks the node from the reference. The node's own keys, including model keys beside its$ref, are checked where the entry's walk checks them: on a property oritemsnode anywhere in the entry (undernot,then,containsoradditionalPropertiestoo). Under anx-*key, such a node's own keys are checked from the reference, but model keys beside its$refare not. Only the node is built. The rest of the entry around it builds nothing and is walked as an unused entry is: its contents are checked, but model keys there that no class reads import, as on dev. (The previously pushed head raised for those, because it walked the whole entry as built. That is also what let the#/$defs/Wrap/properties/innercase below import.)An entry no
$refreaches builds nothing. Its own keys are not checked, so a dereferenced schema that keeps its originals imports as before. Its contents are checked, as on dev, and so are the contents of its$reftargets. Data keywords (default,examples,enum,const) andx-*payloads are values and are not walked. The exception is the node of anx-*payload that a$refpoints at, whether the$refis in the schema or in a definition, used or not: its contents are walked, and so are its own keys when it is a property oritemsnode, but not the payload's other members. A$refinto a data value walks the node it points at for its contents only. A$refheld in an unreached value is not followed. A$defsordefinitionskey holds definitions only as a keyword of the root or of a node reached through schema keywords, so one inside a value, under#/components/...or in anx-*payload is part of that value and is not walked (dev walked it). A property or member nameddefinitionsor$defsis a name, and an entry named like a keyword (properties,items) is an entry. An entry namedpropertiesstill has its own shape left unchecked, as on dev, which read it as a map of properties:patternPropertiesor a keyword beside a combiner at its top imports.A
$refto a map of schemas by name (#/properties,#/$defs/W/properties) is walked one member at a time, so a member named like a keyword is read as a name, as on dev.One reading for a
$refpointer. A key in it is a keyword only where the node holding it is read as a schema. Apropertieskey of any such node holds names, as the walk reads it.$defs,definitions,dependentSchemasandpatternPropertieshold names only as a keyword of a schema reached from the root through schema keywords. A pointer passes only through objects, so a list keyword before another segment holds an object, read as a schema. So a member of#/components/schemasor anx-*payload namedanyOfordefinitionsis a schema whosepropertieshold names, as on dev:#/x-models/anyOf/properties/propertiesis a property namedproperties, and a field key on its propertyitemsis read.A recursive
$refthat the parser leaves unresolved raises the existing "Recursive JSON Schema models are not supported"ValueError, not a pydantic error.Field-scope keys in a definition raise and name a position that reads them: beside the
$ref, or beside theanyOf/oneOfwhen the$refis an arm. TheallOfis offered too for an object definition withpropertieswhen it and each alias hop to it are typed"object"or untyped, since a one-armallOfof anything else fails to import. Foritems, the array property reads only the weight. A definition used as the root reads none. The warning forx-aws-stickler-thresholdon an array of models used to say "declared inside that property's 'items'", which now raises beside the$ref. It now names the definition thatitems$refs, also inside anallOfarm and under a property name holding a.. Where it finds no single array property at the path, it says what holds for inlineitemsand for a$ref.Model keys raise where no class reads them and no doc names the position:
$refonitemsor ananyOf/oneOfarm. This includes such a node anywhere in a$defsentry, outside anx-*key, that a property,itemsor arm$refs, such as#/$defs/List/itemsor#/$defs/W/not/items. The class is built from the target, at the end of an alias chain. The keys beside a target's own$refare still dropped, as on dev, in three places: at the top of another node of an entry (#/$defs/W/not), on a node under anx-*key, and on a target outside$defs(#/components/R);allOfarm (inline or$ref), which is merged into one class at the defaults;$ref, where the root reads the keys beside its$ref.The last two raise only when no other position builds the same object from its keys, counting positions inside any
$reftarget. A$refundernot,additionalPropertiesorifbuilds nothing and does not count. All three also apply inside any$reftarget that a position building a class references, wherever it sits, for example#/components/..., anx-*payload, or undernot,then,additionalPropertiesor anx-*key in a$defsentry.On an object-typed property the same keys warn instead, and import with the keys dropped: beside a
$refon a property typed"object"or a list form that includes it, and on an object-typed property reached only through the root$refor anallOfarm. The warning names the key, its position and where it is read, and says it becomes aValueErrorin 1.1.0. It is issued only once the import builds, so an import that fails anyway, such as a root$refto a property typed["object", "null"], still fails, with no warning. A pointer into a map that no schema keyword holds reads a member named like a keyword as a name, so#/components/schemas/properties/properties/inneris a property too. See Deprecations.Error paths name the keyword. Under
not,then,contains,additionalPropertiesand the other keywords that build no class, the path now includes the keyword ('$defs.W.not[]','not.p'). Dev left it out, and for a typo there named'[]'and'p', nodes that do not exist.A union root (
["object", "null"], rootanyOf/oneOf, or a root$refto either) raisesValueErrorsaying the root must be a single object, rather thanAttributeError: model_fields.Design decision: field-scope keys inside
$defsare rejected, not honoured#340 Gap 1 could have been fixed by honouring the key. We chose to reject it:
$refit.itemsdoes not read field keys, so an honouredx-aws-stickler-thresholdinside a definition would work at a property$refand vanish at anitems$ref. That is the silent drop again, now depending on where the type is used.Addresscan need different weights. The spelling that already works is beside the$ref({"$ref": "#/$defs/Address", "x-aws-stickler-weight": 2.0}), and the error points there.to_json_schema()never writes$defs, so Stickler's own exports are not affected. Pydanticmodel_json_schema()output placesField(json_schema_extra=...)keys either beside the$refor under a definition'sproperties, which are field positions and still accepted.Before and after
Measured on
origin/dev6f76236 and on this branch 45b1553, except the["object"]row, measured onorigin/devc70ca6e and this branch d581b21; Python 3.12.6,sticklerimported from each tree (checked withinspect.getfile).Rowis titledRow.child: {"type": ["object","null"], model-name "ChildRenamed", match-threshold 0.93}DynamicModel,0.7ChildRenamed,0.93infer-unspecified: true,numberchildNumericComparator @ 0.5@ 0.95c: {"type": ["object"], model-name "Row", match-threshold 0.9}DynamicModel,0.7Row,0.9items: ["object","null"]at0.93, element scoring0.9tp 1, fd 0, fp 0tp 0, fd 1, fp 1child: {"type": ["object","null"], "$ref": Inner}, one-character differenceExactComparator,0.00.9$defs.Inner(reached) withx-aws-stickler-thresoldUnrecognized ... on definition '$defs.Inner'$defs.Inner(reached) withx-aws-stickler-threshold: 0.880.7, silent$ref{"$ref": "#/$defs/Inner", "x-aws-stickler-threshold": 0.88}0.880.88$defsbeside inlined copiesExactComparator$defsentryx-*node that only an unused$defsentry$refsx-*payloadnot.items'[]''not[]'x-aws-stickler-aggregateon a definitionhome: {$ref: Addr}pluswork: {allOf: [{$ref: Addr}]}homeisAddress @ 0.93teamvia#/components/schemas/TeamreadingPerson, plusallOf: [{$ref: Person}]team.leadisPerson @ 0.93allOf: [{$ref: Addr}]as the only use of a keyedAddrAllOfModel @ 0.7, keys droppeditems: {"$ref": Row, "x-aws-stickler-match-threshold": 0.93}Row @ 0.7, silent$defs.Rowa: {"$ref": "#/$defs/List/items"},List.items = {"$ref": Row, match-threshold 0.93}items @ 0.7, silent$defs.Rowa: {"$ref": "#/$defs/W/not/items"}, that node{"$ref": Row, match-threshold 0.93}items @ 0.7, silent'$defs.W.not[]', points at$defs.Rowp: {"type": "object", "$ref": Row, "x-aws-stickler-match-threshold": 0.93}Row @ 0.7, silentRow @ 0.7, warns (Deprecations)"type": ["object"]Row @ 0.7, silent"type": ["object", "null"]or["null", "object"]Union[Row, Row, None],ExactComparator, silentOptional[Row],LevenshteinComparator, warnst: {"$ref": "#/x-models/T"},T.properties.wis the propertypaboveT @ 0.7,wisRow @ 0.7'x-models.T.w'a: {"$ref": "#/$defs/W/not/properties/p"},pas abovep @ 0.7, silent'$defs.W.not.p'{"$ref": "#/$defs/Wrap/properties/inner"},inneran object with model-name and match-threshold 0.93DynamicModel @ 0.7, silentinnertyped["object", "null"]AttributeError: model_fieldsValueError, the root must be a single object; no warningh: {"$ref": "#/$defs/W/properties/s"}, another property ofWwith a typed$refand match-threshold 0.93s @ 0.7rows: {"type": "array", "items": {"$ref": Row}, "x-aws-stickler-threshold": 0.9}, at the root, in anallOfarm, or nameda.bDocs
docs/docs/Advanced/dynamic-models.md: the list forms["object", "null"]and["object"]read the same keys as"object"; what a definition reads; where field keys go, with theallOflimited to an object withpropertieswhen it and each alias hop are typed"object"or untyped; where model keys raise and where they warn, including inside any$reftarget a building position references; where a target's own keys are checked.src/stickler/structured_object_evaluator/README.md: the same rules, briefly.CHANGELOG.md, Unreleased: one entry under Changed for the warning, seven under Fixed. None is breaking.Tests
test_unknown_schema_extensions.pyandtest_object_property_threshold.pygo from 70 to 706 cases. New classes includeTestAKeywordIsReadOnlyWhereASchemaHoldsIt,TestOnlyAKeywordOfASchemaHoldsDefinitions,TestARefToAMapOfSchemasReadsItsMembersAsNames,TestAMemberNamedLikeAMapKeywordIsASchema,TestANullableObjectReadsItsModelKeys,TestDefinitionsAreChecked,TestOnlyReachedDefinitionsAreChecked,TestValuesAreNotWalkedAsSchemas,TestAllOfRaisesOnlyWhereNothingReadsTheKeys,TestARefIntoADefinition,TestAListFormTypeBesideARef,TestModelKeysBesideANonRootRef,TestBesideARefUnderAKeywordOfAnEntryandTestTheWarningNamesTheClassAnItemsRefBuildsFrom.src, those assertions pass and only the warning assertion fails.tests/test_docs_build.pyandtests/test_readme_examples.py88 passed;ruff check .clean.components,x-*payloads,$defsand data values,$refs into them, and list-form types: 12,537 import on dev, and every one that raises here raises for a misspelled key (9) or for a Stickler key dev never read there (67).Deprecations
Nothing in this PR is breaking. Breaking here means a public name, parameter or result field removed, renamed or retyped, a default changed, input the docs accept now rejected, or a documented output format changed. Dev's README lists object-level keys as "valid on the root schema or on any object-typed property", so two positions where no class reads them warn rather than raise:
x-aws-stickler-model-name,-match-thresholdor-infer-unspecifiedbeside a$refon a property typed"object"or a list form that includes it (["object", "null"],["null", "object"],["object"]). The class is built from the target at the target's own keys, on dev and on this branch:Row @ 0.7, orDynamicModel @ 0.7for a list form with an untitled target. The branch adds the warning. For["object", "null"]and["null", "object"]the field itself also changes, as Schema round trip silently drops model-scope keys on["object","null"], mapping fields, and union-typed nested models #349 A describes: dev builtUnion[Row, Row, None]withExactComparator, and this branch buildsOptional[Row]with the default comparator. This holds wherever the property sits, for example in a$defsentry (undernot,then,containsoradditionalPropertiestoo), under#/components/..., or in anx-*payload such as#/x-models/T. Where the property is itself the target of a property,itemsoranyOf/oneOf$ref, it warns only as a property node of a$defsentry outside anx-*key. Elsewhere the keys are still dropped with no warning, as on dev (see Not addressed).$refor anallOfarm ({"$ref": "#/$defs/Wrap/properties/inner"}), wherever it sits: in a$defsentry, underitems,notor anx-*key in one, under#/components/..., or in anx-*payload. Dev and this branch both buildDynamicModel @ 0.7orAllOfModel @ 0.7.Both warnings say the key becomes a
ValueErrorin 1.1.0 (follow-up below). An import that fails anyway gives no warning.Every new raise is at a position no doc names for that key: a field key inside a
$defsentry, an object-level key in a definition that builds no class, an object-level key beside a$refonitemsor a combiner arm, on anallOfarm, or on a root$reftarget that is not an object-typed property, and a typo. Dev dropped the key there with no effect on the built model, measured for every key at every such position. The["object", "null"]change moves scores toward what the docs describe. There is one relaxation. A typo, misplaced key,patternPropertiesor keyword beside a combiner used to raise inside anx-*payload or a data value that no$refreaches, and now imports. That includes a payload that only a$refinside another unreached value names (x-other.properties.i = {"$ref": "#/x-models/Team"}). A typo on a property oritemsnode inside a data value that a$refpoints at (#/properties/a/default/properties/p) imports too, and so does a typo in an entry of a$defsinside a value or anx-*payload (default.$defs.U.properties.p). Exports fromto_json_schema()are unaffected.Not addressed
["object","null"], mapping fields, and union-typed nested models #349 B (mapping and plainBaseModelfields export as scalars) and C (Union[ModelA, ModelB]escapes the export guard).x-aws-stickler-aggregatein a definition) is fixed here.$reftargets that are not a whole$defsentry are not checked as a definition at their top: a node of an entry that is not a property oritemsnode (#/$defs/W/not), a node under anx-*key, and a target outside$defs. A typo at the top of#/$defs/W/not,#/$defs/W/x-sub/T,#/x-models/Tor#/components/schemas/Timports, as on dev. So does a model key beside the target's$ref:#/$defs/W/not,#/components/Rand#/components/schemas/W/properties/innereach build at0.7. A typo on a property oritemstarget is still caught, as on dev. (Tracked as a follow-up.)$refs the node does not read it, as on dev. (Tracked as a follow-up.)allOf: [{"$ref": X}]buildsAllOfModelat the defaults, and fails for a scalar, array, mapping or list-typedX. (Tracked as a follow-up.)componentsnamed like a combiner, such ascomponents.schemas.anyOf, is still read by the walk as that combiner, as on dev, so it raises beside other members. A$refpointer through it reads it as a schema. (Tracked as a follow-up.)Overlap
This PR and #408 (
fix/334-348-importer-defaults) touch the same importer. Trial-merged on top of current dev, the importer merges cleanly and the combined suite passes.CHANGELOG.mdand the extension table indynamic-models.mdconflict. Re-check on the final heads.