Repository navigation
fix(340): read and check Stickler extensions inside $defs - #402
Thanatos9404 wants to merge 1 commit into
Conversation
The extension walk entered each $defs / definitions entry with no scope,
so _reject_unknown_extensions never ran on a definition and a misspelled
key there imported cleanly. And json-schema-to-pydantic keeps a
definition's x- keys only in the config of the class it generates (none
at all for a scalar or array definition), where nothing reads the field
keys. An object property reached through $ref therefore scored against
the default 0.7 while the same object written inline used its declared
x-aws-stickler-threshold.
_prepare_schema now copies a referenced definition's field keys onto
each property that references it, directly or through the
anyOf-with-null wrapper pydantic writes for Optional[Model] (or a
single-arm allOf). A key the property states beside the $ref wins, and
along a chain of references the nearer definition wins. Keys are taken
one at a time, except that a definition's comparator config is not
carried onto a property that names its own comparator. The walk checks
every definition the way it checks a property ("field_or_model" for an
object, "field" otherwise), with the definition's path in the message.
test_via_defs_silently_falls_back and test_the_same_typo_inside_defs_is_not
pinned the old behaviour, as their class docstring said they would; they
now assert the threshold is read and the typo raises.
Closes awslabs#340
Security Scan ResultsASH Security Scan Report
Scan Metadata
SummaryScanner ResultsThe table below shows findings by scanner, with status based on severity thresholds and dependencies:
Top 2 HotspotsFiles with the highest number of security findings:
Detailed FindingsShow 4 actionable findingsFinding 1: SECRET-HEX-HIGH-ENTROPY-STRING
Description: Code Snippet: Finding 2: B108
Description: Code Snippet: Finding 3: B307
Description: Code Snippet: Finding 4: B307
Description: Code Snippet: Report generated by Automated Security Helper (ASH) at 2026-10-16T15:47:42+00:00 |
|
Thanks @Thanatos9404, this is careful work, and reviewing it settled a design question for us. We're going with #407 for #340 instead, and closing this one. The reason is the shape of the problem rather than the quality of the PR. Honouring a field key inside a definition means reading it at every place that can reference the definition, and those places don't all read field keys. Reviewing this PR against
Each new reference spelling would need its own special case in both the carry and the walker. #407 instead raises on a field key inside a definition, pointing to the spelling that already works (beside the If you're up for another one in this area, #349 parts B and C are open and unclaimed:
The |
Pull Request
Issue Reference
Closes #340
Description of Changes
Both gaps in #340 come from the same place: nothing read a Stickler key written on a
$defs/definitionsentry. This reads a definition's field keys at every property that references it, and checks every definition for misspelled keys the way a property is checked.Changes Made
json_schema_importer.py,_validate_supported_shapes: each entry under$defs/definitionsis walked with the scope a property gets (field_or_modelfor an object,fieldotherwise) and its own path ($defs.Inner), instead ofscope=None(dev :930-932).json_schema_importer.py,_prepare_schema: a new_carry_definition_extensionscopies the five documented field keys from a referenced definition onto the property that references it, before the schema reachesjson-schema-to-pydantic. Two small module helpers find the$refa property stands for (its own, or the single non-null arm of ananyOf/oneOf/allOf) and resolve a local JSON pointer.tests/structured_object_evaluator/test_json_schema_defs_extensions.py, 18 tests (28 cases), and the two tests intest_object_property_threshold.pythat pinned the gap, updated (see below).CHANGELOG.md: one Breaking entry under[Unreleased]/ Fixed.docs/docs/Advanced/dynamic-models.md: a short paragraph under the extension table with the$defsrule.Why These Changes Are Needed
There were two separate drops, and fixing only the first would have left a correctly spelled key passing the check and still being ignored:
$defsmapping scopemodeland then walked each definition withscope=None(dev :911, :930-932), so_reject_unknown_extensionsnever saw a definition's own keys. Properties inside a definition were already checked.json-schema-to-pydanticbuilds a field'sjson_schema_extrafrom the property node, which for{"$ref": ...}has no keys. The definition's keys go only into the generated class'smodel_config["json_schema_extra"], which_build_nested_modelreads for the object-level keys only (dev :583). For a scalar or array definition the library keeps no keys at all.Measured on
devf81a33e and on this branch (dc723d8), resolved threshold unless stated:x-aws-stickler-threshold: 0.88{"$ref": "#/$defs/Inner"}{"anyOf": [{"$ref": ...}, {"type": "null"}]}#/definitions/Inner$defs, threshold 0.8, one leaf wrong: field scoreExactComparatorat 0.9x-aws-stickler-thresoldinline$defsThe
anyOfrow is the shape pydantic 2.12 writes forOptional[Model], so most generated schemas reach their definitions that way.Precedence
The 1.0.0 entry left open whether a
$defsextension belongs to the definition or to each referencing site. This takes both, with the site winning, which is what a$refmeans (the referenced schema applies at that location) and what writing the definition inline would give:$ref, or beside theanyOfthat wraps it, wins for that property. Pydantic itself puts a field's owndescriptionthere ({"$ref": "#/$defs/A", "description": "desc"}), so it is where a per-field setting already goes.-comparator-config: carried, aNumericComparatorconfig madeExactComparatorwarn aboutrelative_tolerance, a key nobody wrote at that property. A property that states only a config keeps the definition's comparator, and its config replaces the definition's.Alias: {"$ref": "#/$defs/I"}), the nearer definition wins.Other shapes
Optionalproperty sharing one definition).$defs(#/$defs/Outer/$defs/I) anddefinitions: read and checked; the message names$defs.Outer.$defs.Iordefinitions.I.A -> B -> Achain stops and gets the same error.items: not a property, so no field key is carried there, and the element class still reads its own object-level keys as before (the array field keeps the0.5it gets with no$defs). A field key on a definition used only asitemsis therefore not flagged, where the inline spelling raises. Catching that needs checking each definition once per reference site; I left it out to keep this small.What now raises
Marked Breaking because schemas that imported on
devnow raise in three cases, all of them keys that were being dropped:match-threshold,model-name) on a definition that is not an object. Written on a property,{"$ref": "#/$defs/I", "x-aws-stickler-match-threshold": 0.9}already raised ondev; as the body of an alias definition it imported and built the class at 0.7;"auto"on an object definition, each with the same error as the inline spelling. Since the value is read at the property, the message names the property (for field 'inner').Scores move only for schemas that declared a field key inside
$defs.Tests that pinned the old behaviour
The issue names both. They asserted the gap, and their class docstring said they would fail once it was fixed:
TestTheKeyIsStillDroppedInsideDefsis nowTestTheKeyIsReadInsideDefs.test_via_defs_silently_falls_backis nowtest_via_defs_it_is_read: it asserts 0.88 instead of 0.7, and still that no threshold warning is raised.test_the_same_typo_inside_defs_is_notis nowtest_the_same_typo_inside_defs_is_rejected_too: it asserts theValueError, the suggestion and$defs.Innerin the message, instead of a clean import at 0.7.That docstring also said to delete the "Known gap" paragraph from the CHANGELOG in the same commit. The paragraph is now in the released
[1.0.0]section, so I left it and the[Unreleased]entry says the gap is closed. Happy to edit the 1.0.0 text instead.Relation to #348 and #334
Carried keys go through the same code as inline ones, so the fixes planned there apply to
$defswith no extra work, and nothing here changes the defaults those issues are about:x-aws-stickler-comparator-config: {"threshold": 0.9}resolves 0.5 here, exactly like the inline spelling. Only declared keys are carried, so passingNonefor an absent threshold will keep working.extensions.get("clip_under_threshold", True)for a carried key as for an inline one.x-aws-stickler-comparatoron an object definition is now validated and then dropped exactly like the inline case (a bogus name raises,ExactComparatorresolves toLevenshteinComparator). Ondevit was not read at all. If item 7 is fixed by raising, object definitions will raise too.0.7(dev :432) is untouched.Testing
signal.SIGALRM; details below)Windows, Python 3.12.5,
uv sync --frozen --extra llm --no-group docs(CI also installs thebertextra).inspect.getfile(stickler)pointed at this checkout'ssrc/stickler/__init__.pyfor the branch runs. Thedevruns useddevf81a33e'ssrc/onPYTHONPATH, andinspect.getfilepointed there.devf81a33esrc/test_object_property_threshold.pyThe 4 that pass on
devpin behaviour this must keep or thatdevgets right by not carrying anything: the arrayitemscase, the two recursion cases, and "a property naming its own comparator does not take the definition's config". The 6 failures are the same on both trees: 5 tests inTestRealisticDeepNestingandtest_integrationintest_realistic_deep_nesting.py, allAttributeError: module 'signal' has no attribute 'SIGALRM'. Linux CI runs them.uv run ruff check .gives the same 16 findings on both trees, all inexamples/notebooks/*.ipynbandexamples/scripts/llm_comparator_demo.py. On the three changed Python filesruff checkpasses.ruff format --checkpasses for the importer and the new test file, and flagstest_object_property_threshold.pyfor one docstring at line 448 that it also flags ondev; this PR does not touch that line.mkdocs buildgives the same 9 warnings on both trees.Reviewers
@sromoam
Checklist
CHANGELOG.mdentry added under[Unreleased], or not needed becausenothing user-visible changed (see RELEASING.md)
Additional Notes
**Breaking:**, the way e638ea2 marked [BUG]: model_from_json silently ignores every unrecognized config key, so "threshhold": 0.99 builds at 0.5 #350 (a key that was dropped silently now raises), and like the StructuredModel fields typed date, datetime, time, Decimal, UUID or Enum score 0.0 against an identical value #383 entry in this milestone and the [BUG]: x-aws-stickler-threshold is silently dropped on an object-typed property, while weight is honoured #317 entry this closes.By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.