Skip to content

fix(json-schema): read model keys on nullable objects, check $defs entries, flag model keys no class reads - #407

Merged
sromoam merged 65 commits into
devfrom
fix/349-340-schema-import-holes
Nov 18, 2026
Merged

sromoam merged 65 commits into
devfrom
fix/349-340-schema-import-holes

Conversation

@sromoam

@sromoam sromoam commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Closes #340.
Refs #349 (part A; parts B and C are not addressed).

Root causes

#349 A. _prepare_schema rewrites "type": ["object", "null"] to anyOf before parsing. The x-aws-stickler-* keys stayed beside the anyOf, and the arms were built without them, so the class was built as DynamicModel at 0.7 while its field keys were honoured. 0.7.0 read the name and threshold, so this is a 1.0.0 regression. Beside a $ref, the rewrite also copied the $ref onto the null arm, so the node became a union of two classes compared with ExactComparator.

#340. _validate_supported_shapes entered each $defs/definitions body with no scope, so a definition's own keys were never checked. A typo there imported silently where the same typo inline raised, and x-aws-stickler-threshold: 0.88 inside 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 $ref targets 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 $ref to an object builds what "array" builds, and a shape where "object" fails to import beside the same $ref fails the same way for the list form. Beside a $ref to 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 $ref reaches is checked under its own scope. With properties it accepts only the model-scope keys, plus x-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 $ref to 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 or items node anywhere in the entry (under not, then, contains or additionalProperties too). Under an x-* key, such a node's own keys are checked from the reference, but model keys beside its $ref are 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/inner case below import.)

  • An entry no $ref reaches 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 $ref targets. Data keywords (default, examples, enum, const) and x-* payloads are values and are not walked. The exception is the node of an x-* payload that a $ref points at, whether the $ref is 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 or items node, but not the payload's other members. A $ref into a data value walks the node it points at for its contents only. A $ref held in an unreached value is not followed. A $defs or definitions key 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 an x-* payload is part of that value and is not walked (dev walked it). A property or member named definitions or $defs is a name, and an entry named like a keyword (properties, items) is an entry. An entry named properties still has its own shape left unchecked, as on dev, which read it as a map of properties: patternProperties or a keyword beside a combiner at its top imports.

  • A $ref to 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 $ref pointer. A key in it 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. $defs, definitions, dependentSchemas and patternProperties hold 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/schemas or an x-* payload named anyOf or definitions is a schema whose properties hold names, as on dev: #/x-models/anyOf/properties/properties is a property named properties, and a field key on its property items is read.

  • A recursive $ref that 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 the anyOf/oneOf when the $ref is an arm. The allOf is offered too for an object definition with properties when it and each alias hop to it are typed "object" or untyped, since a one-arm allOf of anything else fails to import. For items, the array property reads only the weight. A definition used as the root reads none. The warning for x-aws-stickler-threshold on an array of models used to say "declared inside that property's 'items'", which now raises beside the $ref. It now names the definition that items $refs, also inside an allOf arm and under a property name holding a .. Where it finds no single array property at the path, it says what holds for inline items and for a $ref.

  • Model keys raise where no class reads them and no doc names the position:

    • beside a non-root $ref on items or an anyOf/oneOf arm. This includes such a node anywhere in a $defs entry, outside an x-* key, that a property, items or arm $refs, such as #/$defs/List/items or #/$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 $ref are still dropped, as on dev, in three places: at the top of another node of an entry (#/$defs/W/not), on a node under an x-* key, and on a target outside $defs (#/components/R);
    • on an allOf arm (inline or $ref), which is merged into one class at the defaults;
    • on an object reached through a root $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 $ref target. A $ref under not, additionalProperties or if builds nothing and does not count. All three also apply inside any $ref target that a position building a class references, wherever it sits, for example #/components/..., an x-* payload, or under not, then, additionalProperties or an x-* key in a $defs entry.

  • On an object-typed property the same keys warn instead, and import with the keys dropped: beside a $ref on a property typed "object" or a list form that includes it, and on an object-typed property reached only through the root $ref or an allOf arm. The warning names the key, its position and where it is read, and says it becomes a ValueError in 1.1.0. It is issued only once the import builds, so an import that fails anyway, such as a root $ref to 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/inner is a property too. See Deprecations.

  • Error paths name the keyword. Under not, then, contains, additionalProperties and 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"], root anyOf/oneOf, or a root $ref to either) raises ValueError saying the root must be a single object, rather than AttributeError: model_fields.

Design decision: field-scope keys inside $defs are rejected, not honoured

#340 Gap 1 could have been fixed by honouring the key. We chose to reject it:

  • A definition is a type, and several positions can $ref it. items does not read field keys, so an honoured x-aws-stickler-threshold inside a definition would work at a property $ref and vanish at an items $ref. That is the silent drop again, now depending on where the type is used.
  • A field key is about one use of the type, and two properties using the same Address can 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.
  • Measured on dev, a field key inside a definition was never read at any reference position. Rejecting it never takes away a working configuration.
  • to_json_schema() never writes $defs, so Stickler's own exports are not affected. Pydantic model_json_schema() output places Field(json_schema_extra=...) keys either beside the $ref or under a definition's properties, which are field positions and still accepted.

Before and after

Measured on origin/dev 6f76236 and on this branch 45b1553, except the ["object"] row, measured on origin/dev c70ca6e and this branch d581b21; Python 3.12.6, stickler imported from each tree (checked with inspect.getfile). Row is titled Row.

Schema dev branch
child: {"type": ["object","null"], model-name "ChildRenamed", match-threshold 0.93} DynamicModel, 0.7 ChildRenamed, 0.93
same, infer-unspecified: true, number child NumericComparator @ 0.5 @ 0.95
c: {"type": ["object"], model-name "Row", match-threshold 0.9} DynamicModel, 0.7 Row, 0.9
items: ["object","null"] at 0.93, element scoring 0.9 tp 1, fd 0, fp 0 tp 0, fd 1, fp 1
child: {"type": ["object","null"], "$ref": Inner}, one-character difference ExactComparator, 0.0 Levenshtein, 0.9
$defs.Inner (reached) with x-aws-stickler-thresold imports raises, Unrecognized ... on definition '$defs.Inner'
$defs.Inner (reached) with x-aws-stickler-threshold: 0.88 0.7, silent raises, points beside the $ref
{"$ref": "#/$defs/Inner", "x-aws-stickler-threshold": 0.88} 0.88 0.88
dereferenced schema keeping $defs beside inlined copies weight 3.0, ExactComparator same
typo in a property of an unused $defs entry raises raises
typo inside an x-* node that only an unused $defs entry $refs raises raises
typo in an unreached x-* payload raises imports
typo under the root's not.items raises at '[]' raises at 'not[]'
x-aws-stickler-aggregate on a definition imports imports
home: {$ref: Addr} plus work: {allOf: [{$ref: Addr}]} home is Address @ 0.93 same
team via #/components/schemas/Team reading Person, plus allOf: [{$ref: Person}] team.lead is Person @ 0.93 same
allOf: [{$ref: Addr}] as the only use of a keyed Addr AllOfModel @ 0.7, keys dropped raises
items: {"$ref": Row, "x-aws-stickler-match-threshold": 0.93} Row @ 0.7, silent raises, points at $defs.Row
a: {"$ref": "#/$defs/List/items"}, List.items = {"$ref": Row, match-threshold 0.93} items @ 0.7, silent raises, points at $defs.Row
a: {"$ref": "#/$defs/W/not/items"}, that node {"$ref": Row, match-threshold 0.93} items @ 0.7, silent raises at '$defs.W.not[]', points at $defs.Row
p: {"type": "object", "$ref": Row, "x-aws-stickler-match-threshold": 0.93} Row @ 0.7, silent Row @ 0.7, warns (Deprecations)
same with "type": ["object"] Row @ 0.7, silent same, warns
same with "type": ["object", "null"] or ["null", "object"] Union[Row, Row, None], ExactComparator, silent Optional[Row], LevenshteinComparator, warns
t: {"$ref": "#/x-models/T"}, T.properties.w is the property p above T @ 0.7, w is Row @ 0.7 same, warns at 'x-models.T.w'
a: {"$ref": "#/$defs/W/not/properties/p"}, p as above p @ 0.7, silent same, warns at '$defs.W.not.p'
{"$ref": "#/$defs/Wrap/properties/inner"}, inner an object with model-name and match-threshold 0.93 DynamicModel @ 0.7, silent same, warns "on object '$defs.Wrap.properties.inner' is not read when it is reached through the root '$ref'"
same with inner typed ["object", "null"] AttributeError: model_fields ValueError, the root must be a single object; no warning
h: {"$ref": "#/$defs/W/properties/s"}, another property of W with a typed $ref and match-threshold 0.93 s @ 0.7 same (the previously pushed head raised)
rows: {"type": "array", "items": {"$ref": Row}, "x-aws-stickler-threshold": 0.9}, at the root, in an allOf arm, or named a.b warns "declared inside that property's 'items'" warns "declared on definition '$defs.Row', where its 'items' '$ref' leads"

Docs

  • 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 the allOf limited to an object with properties when it and each alias hop are typed "object" or untyped; where model keys raise and where they warn, including inside any $ref target 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.py and test_object_property_threshold.py go from 70 to 706 cases. New classes include TestAKeywordIsReadOnlyWhereASchemaHoldsIt, TestOnlyAKeywordOfASchemaHoldsDefinitions, TestARefToAMapOfSchemasReadsItsMembersAsNames, TestAMemberNamedLikeAMapKeywordIsASchema, TestANullableObjectReadsItsModelKeys, TestDefinitionsAreChecked, TestOnlyReachedDefinitionsAreChecked, TestValuesAreNotWalkedAsSchemas, TestAllOfRaisesOnlyWhereNothingReadsTheKeys, TestARefIntoADefinition, TestAListFormTypeBesideARef, TestModelKeysBesideANonRootRef, TestBesideARefUnderAKeywordOfAnEntry and TestTheWarningNamesTheClassAnItemsRefBuildsFrom.
  • Each warning test asserts the built class and match threshold before the warning. Run against dev's src, those assertions pass and only the warning assertion fails.
  • Full suite on this head with dev merged in: 5111 passed, 13 skipped, 1 xfailed; tests/test_docs_build.py and tests/test_readme_examples.py 88 passed; ruff check . clean.
  • Checked against dev with 94,072 generated schemas mixing keyword-named properties and members of components, x-* payloads, $defs and 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-threshold or -infer-unspecified beside a $ref on 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, or DynamicModel @ 0.7 for 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 built Union[Row, Row, None] with ExactComparator, and this branch builds Optional[Row] with the default comparator. This holds wherever the property sits, for example in a $defs entry (under not, then, contains or additionalProperties too), under #/components/..., or in an x-* payload such as #/x-models/T. Where the property is itself the target of a property, items or anyOf/oneOf $ref, it warns only as a property node of a $defs entry outside an x-* key. Elsewhere the keys are still dropped with no warning, as on dev (see Not addressed).
  • The same keys on an object-typed property that no position builds, reached only through the root $ref or an allOf arm ({"$ref": "#/$defs/Wrap/properties/inner"}), wherever it sits: in a $defs entry, under items, not or an x-* key in one, under #/components/..., or in an x-* payload. Dev and this branch both build DynamicModel @ 0.7 or AllOfModel @ 0.7.

Both warnings say the key becomes a ValueError in 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 $defs entry, an object-level key in a definition that builds no class, an object-level key beside a $ref on items or a combiner arm, on an allOf arm, or on a root $ref target 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, patternProperties or keyword beside a combiner used to raise inside an x-* payload or a data value that no $ref reaches, and now imports. That includes a payload that only a $ref inside another unreached value names (x-other.properties.i = {"$ref": "#/x-models/Team"}). A typo on a property or items node inside a data value that a $ref points at (#/properties/a/default/properties/p) imports too, and so does a typo in an entry of a $defs inside a value or an x-* payload (default.$defs.U.properties.p). Exports from to_json_schema() are unaffected.

Not addressed

  • Schema round trip silently drops model-scope keys on ["object","null"], mapping fields, and union-typed nested models #349 B (mapping and plain BaseModel fields export as scalars) and C (Union[ModelA, ModelB] escapes the export guard).
  • JSON Schema importer: definition vs inline object classification, and x-aws-stickler-aggregate in $defs (from #407) #463 item 1: an object definition is classified differently from the same node inline. Item 2 (x-aws-stickler-aggregate in a definition) is fixed here.
  • Some $ref targets that are not a whole $defs entry are not checked as a definition at their top: a node of an entry that is not a property or items node (#/$defs/W/not), a node under an x-* key, and a target outside $defs. A typo at the top of #/$defs/W/not, #/$defs/W/x-sub/T, #/x-models/T or #/components/schemas/T imports, as on dev. So does a model key beside the target's $ref: #/$defs/W/not, #/components/R and #/components/schemas/W/properties/inner each build at 0.7. A typo on a property or items target is still caught, as on dev. (Tracked as a follow-up.)
  • A field key on a property node is valid where it sits, but another property that $refs the node does not read it, as on dev. (Tracked as a follow-up.)
  • A one-arm allOf: [{"$ref": X}] builds AllOfModel at the defaults, and fails for a scalar, array, mapping or list-typed X. (Tracked as a follow-up.)
  • Raising for the two deprecated positions in 1.1.0. (Tracked as a follow-up.)
  • A member of components named like a combiner, such as components.schemas.anyOf, is still read by the walk as that combiner, as on dev, so it raises beside other members. A $ref pointer 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.md and the extension table in dynamic-models.md conflict. Re-check on the final heads.

…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.
@sromoam sromoam added this to the 1.0.1 (Minor) milestone Oct 16, 2026
@sromoam
sromoam requested a review from vawsgit October 16, 2026 15:31
@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-11-18T18:30:24+00:00
  • Time since scan: 3 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-11-18T18:26:43+00:00
  • ASH version: 3.1.2

Summary

Scanner Results

The table below shows findings by scanner, with status based on severity thresholds and dependencies:

  • Severity levels:
    • Suppressed (S): Findings that have been explicitly suppressed and don't affect scanner status
    • Critical (C): Highest severity findings that require immediate attention
    • High (H): Serious findings that should be addressed soon
    • Medium (M): Moderate risk findings
    • Low (L): Lower risk findings
    • Info (I): Informational findings with minimal risk
  • Duration (Time): Time taken by the scanner to complete its execution
  • Actionable: Number of findings at or above the threshold severity level that require attention
  • Result:
    • PASSED = No findings at or above threshold
    • FAILED = Findings at or above threshold
    • MISSING = Required dependencies not available
    • SKIPPED = Scanner explicitly disabled
    • ERROR = Scanner execution error
  • Threshold: The minimum severity level that will cause a scanner to fail
    • Thresholds: ALL, LOW, MEDIUM, HIGH, CRITICAL
    • Source: Values in parentheses indicate where the threshold is set:
      • global (global_settings section in the ASH_CONFIG used)
      • config (scanner config section in the ASH_CONFIG used)
      • scanner (default configuration in the plugin, if explicitly set)
  • Statistics calculation:
    • All statistics are calculated from the final aggregated SARIF report
    • Suppressed findings are counted separately and do not contribute to actionable findings
    • Scanner status is determined by comparing actionable findings to the threshold
Scanner Suppressed Critical High Medium Low Info Actionable Result Threshold
bandit 0 0 0 0 7061 0 0 PASSED MEDIUM (global)
cdk-nag 0 0 0 0 0 0 0 PASSED MEDIUM (global)
cfn-nag 0 0 0 0 0 0 0 MISSING MEDIUM (global)
checkov 0 0 0 0 0 0 0 PASSED MEDIUM (global)
detect-secrets 0 0 0 0 0 0 0 PASSED MEDIUM (global)
grype 0 0 0 0 0 0 0 MISSING MEDIUM (global)
npm-audit 0 0 0 0 0 0 0 PASSED MEDIUM (global)
opengrep 0 0 0 0 0 0 0 MISSING MEDIUM (global)
semgrep 3 0 0 0 0 0 0 PASSED MEDIUM (global)
syft 0 0 0 0 0 0 0 MISSING MEDIUM (global)

Report generated by Automated Security Helper (ASH) at 2026-11-18T18:30:25+00:00

@vawsgit vawsgit left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

needs changes

["object","null"] model keys and pydantic model_json_schema() output work as described. Three blockers:

  1. json_schema_importer.py:189. The new "definition" scope accepts model keys on every $defs object, but they are silently dropped when the definition is reached through allOf or a root $ref. A declared match-threshold: 0.93 builds at 0.7 with no error. #407 (comment)
  2. json_schema_importer.py:183. A definition used from items raises "belongs on the property beside its $ref". Moving the key there then raises "is not read on object a[]". The author has no working position for the key. #407 (comment)
  3. README.md:246 and docs/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 raises AttributeError: 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.
@sromoam

sromoam commented Oct 19, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review, @vawsgit. All five are addressed in c54d83b, and I merged current dev in.

  • Model keys now raise wherever no class reads them: allOf arms, definitions reached through allOf or a root $ref, and definitions without properties.
  • The items error names a position that works.
  • A union root gets a clear ValueError, and the docs now describe only the nested list form.

22 new tests. Full suite: 3013 passed. Ready for another look.

@sromoam
sromoam requested a review from vawsgit October 19, 2026 16:56
body,
f"{path}.{key}.{name}" if path else f"{key}.{name}",
"definition"
if isinstance(body, dict) and "properties" in body

@vawsgit vawsgit Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 (scope field_or_model).
  • $defs.M with 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Filed as #463, item 1.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread CHANGELOG.md Resolved
elif key == "items":
visit(value, f"{path}[]" if path else "[]")
else:
visit(value, f"{path}.{key}" if path else key)

@vawsgit vawsgit Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4c5bcf0. Data keywords (default, examples) and x-* payloads are no longer walked as schemas, and an unreached definition is not walked.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread docs/docs/Advanced/dynamic-models.md Resolved

@vawsgit vawsgit left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

needs changes

All three earlier blockers are fixed on c54d83b, and both optional items are done. One blocker remains:

  1. json_schema_importer.py:1065. _reject_unread_model_keys raises when any allOf arm reaches a keyed definition, even when another property $refs the same definition and reads its keys. A schema with home: {$ref Addr} and work: {allOf: [{$ref Addr}]} builds Address at 0.93 on dev. 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)
  2. 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 vawsgit left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

  1. json_schema_importer.py:1065 The allOf blocker 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 $defs entry.
  2. json_schema_importer.py:970 Every $defs entry 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.
_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.
@sromoam sromoam changed the title fix(json-schema)!: read model keys on ["object","null"] and check $defs bodies (#340, #349 part A) fix(json-schema): read model keys on nullable objects, check $defs entries, flag model keys no class reads Nov 18, 2026
@sromoam
sromoam requested a review from vawsgit November 18, 2026 17:06
@digalaviz

Copy link
Copy Markdown
Contributor

thanks for this. the ["object","null"] fix works: the example with x-aws-stickler-model-name and a match threshold of 0.93 now loads as Foo at 0.93, where 1.0.1 gave DynamicModel at 0.7.

one thing to look at before 1.0.2. on d581b21, 106 of 1279 schemas taken from this PR's tests load on 1.0.1 and now raise ValueError (a field key inside a $defs entry, a model key beside an items $ref, among others). the scope on #340 from 11-03 had these as warnings until 1.1.0. the suite passes on a trial merge with dev.

would you be open to keeping the 1.0.2 PR to the ["object","null"] fix, with the new raises as warnings, and moving the rest to a 1.1.0 PR?

@vawsgit vawsgit left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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:

  1. The allOf check missed readers in $ref targets outside $defs: fixed. Every resolved $ref target is now queued with the reading position's built flag (
    inner.add(id(target))
    elif target is not None and target_parts:
    # Outside `$defs` the target may sit where the walk does not
    ). I ran the #/components/Person schema on both trees. On dev and on head, team.lead builds Person at 0.93, and employee (allOf) builds AllOfModel at 0.7. The x-models variant also matches dev. Removing that queue branch makes 26 tests fail.
  2. CHANGELOG.md said "loses no working configuration": fixed. The sentence is gone. The replacement claim, "Every key that now raises was dropped in silence" (

    stickler/CHANGELOG.md

    Lines 135 to 138 in d581b21

    or a data value, or a property named so, holds none, so a `$ref` into it
    checks no definition, as before. Every key that
    now raises was dropped in silence
    (`x-aws-stickler-threshold: 0.88` in `$defs` gave `0.7`). `to_json_schema()`
    ), 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.
  3. The "beside its $ref" advice failed for a union arm: fixed. The error now names the anyOf/oneOf/allOf. Following the advice works: anyOf with a threshold gives 0.9, and allOf with a weight gives 2.0. A scalar definition is not offered allOf, because a one-arm allOf of 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 dev and llm extras: 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.md and the README. CI, the version floors and dead code are unchanged.

Non-blocking (low):

  • # Issued only once the import builds: one that fails anyway, such as a
    # root `$ref` to a property typed `["object", "null"]`, would otherwise
    # warn that a key "is ignored" with advice that cannot be followed. No
    # fields fails the import at the caller.
    if fields:
    for message in unread_warnings:
    warnings.warn(message, UserWarning)
    : 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: p is {"type":"object","$ref":"#/$defs/Row","x-aws-stickler-match-threshold":0.93}, and rows is {"type":"array","items":{"$ref":"#/$defs/Row"},"x-aws-stickler-comparator":"ExactComparator"}. The import warns about p, then raises List[StructuredModel] ... cannot have a 'comparator'.
  • scope = "value_definition"
    if "properties" in body:
    scope = "definition"
    : model keys on a definition that has both $ref and properties are still dropped silently, as on dev. The definition gets scope "definition" and accepts the keys, then builds the $ref target (Row at 0.7).

@sromoam

sromoam commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

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 x-aws-stickler-* key or a key at a position no class reads, now raising instead of being silently ignored, is a fix rather than a breaking change. The 106 schemas you found load on 1.0.1 only because their keys are dropped without a word, which is the confusion this fixes. Each error names the key, where it sits, and where to put it. #408 makes the same call for out-of-range thresholds.

Where the docs did accept a key (a model key beside a $ref on an object-typed property, or on one reached only through the root $ref or an allOf arm), it warns in 1.0.2 and keeps importing as before, and becomes an error in 1.1.0.

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.

@sromoam
sromoam merged commit 13a682c into dev Nov 18, 2026
15 checks passed
@sromoam
sromoam deleted the fix/349-340-schema-import-holes branch November 18, 2026 21:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Stickler threshold & extension typo-validation not applied to objects referenced via $ref/$defs

3 participants