Skip to content

fix(340): read and check Stickler extensions inside $defs - #402

Closed
Thanatos9404 wants to merge 1 commit into
awslabs:devfrom
Thanatos9404:bugfix/340-defs-extensions
Closed

Thanatos9404 wants to merge 1 commit into
awslabs:devfrom
Thanatos9404:bugfix/340-defs-extensions

Conversation

@Thanatos9404

Copy link
Copy Markdown
Contributor

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 / definitions entry. 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 / definitions is walked with the scope a property gets (field_or_model for an object, field otherwise) and its own path ($defs.Inner), instead of scope=None (dev :930-932).
  • json_schema_importer.py, _prepare_schema: a new _carry_definition_extensions copies the five documented field keys from a referenced definition onto the property that references it, before the schema reaches json-schema-to-pydantic. Two small module helpers find the $ref a property stands for (its own, or the single non-null arm of an anyOf / oneOf / allOf) and resolve a local JSON pointer.
  • New tests/structured_object_evaluator/test_json_schema_defs_extensions.py, 18 tests (28 cases), and the two tests in test_object_property_threshold.py that 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 $defs rule.

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:

  1. The walk gave the $defs mapping scope model and then walked each definition with scope=None (dev :911, :930-932), so _reject_unknown_extensions never saw a definition's own keys. Properties inside a definition were already checked.
  2. json-schema-to-pydantic builds a field's json_schema_extra from the property node, which for {"$ref": ...} has no keys. The definition's keys go only into the generated class's model_config["json_schema_extra"], which _build_nested_model reads for the object-level keys only (dev :583). For a scalar or array definition the library keeps no keys at all.

Measured on dev f81a33e and on this branch (dc723d8), resolved threshold unless stated:

schema dev this branch
object property inline, x-aws-stickler-threshold: 0.88 0.88 0.88
the same object through {"$ref": "#/$defs/Inner"} 0.7 0.88
through {"anyOf": [{"$ref": ...}, {"type": "null"}]} 0.7 0.88
through #/definitions/Inner 0.7 0.88
four-leaf child via $defs, threshold 0.8, one leaf wrong: field score 0.7778 0.0
scalar definition naming ExactComparator at 0.9 Levenshtein, 0.5 Exact, 0.9
x-aws-stickler-thresold inline ValueError ValueError
the same typo inside $defs imports, 0.7 ValueError, "Did you mean 'x-aws-stickler-threshold'?"

The anyOf row is the shape pydantic 2.12 writes for Optional[Model], so most generated schemas reach their definitions that way.

Precedence

The 1.0.0 entry left open whether a $defs extension belongs to the definition or to each referencing site. This takes both, with the site winning, which is what a $ref means (the referenced schema applies at that location) and what writing the definition inline would give:

  • A definition's field keys apply to every property that references it, as if written on that property.
  • A key written beside the $ref, or beside the anyOf that wraps it, wins for that property. Pydantic itself puts a field's own description there ({"$ref": "#/$defs/A", "description": "desc"}), so it is where a per-field setting already goes.
  • Keys are taken one at a time: a property that states only a weight still gets the definition's threshold.
  • The exception is the comparator config, which belongs to the comparator it was written for. A property that names its own comparator does not take the definition's -comparator-config: carried, a NumericComparator config made ExactComparator warn about relative_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.
  • Along a chain of references (Alias: {"$ref": "#/$defs/I"}), the nearer definition wins.

Other shapes

  • One definition used from several properties: each property gets its own copy and its own overrides (tested with a plain, an overriding and an Optional property sharing one definition).
  • Nested $defs (#/$defs/Outer/$defs/I) and definitions: read and checked; the message names $defs.Outer.$defs.I or definitions.I.
  • Recursion: a self-referencing definition still gets the existing "Recursive JSON Schema models are not supported" error. The carry follows a chain with a seen-set, so a cyclic A -> B -> A chain stops and gets the same error.
  • Array 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 the 0.5 it gets with no $defs). A field key on a definition used only as items is 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 dev now raise in three cases, all of them keys that were being dropped:

  • a misspelled key in any definition, including one nothing references;
  • an object-level key (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 on dev; as the body of an alias definition it imported and built the class at 0.7;
  • an invalid value inside a referenced definition: a threshold of 5, an unknown comparator, or "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:

  • TestTheKeyIsStillDroppedInsideDefs is now TestTheKeyIsReadInsideDefs.
  • test_via_defs_silently_falls_back is now test_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_not is now test_the_same_typo_inside_defs_is_rejected_too: it asserts the ValueError, the suggestion and $defs.Inner in 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 $defs with no extra work, and nothing here changes the defaults those issues are about:

Testing

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing completed
  • All existing tests pass (apart from 6 tests that need the POSIX-only signal.SIGALRM; details below)

Windows, Python 3.12.5, uv sync --frozen --extra llm --no-group docs (CI also installs the bert extra). inspect.getfile(stickler) pointed at this checkout's src/stickler/__init__.py for the branch runs. The dev runs used dev f81a33e's src/ on PYTHONPATH, and inspect.getfile pointed there.

uv run pytest tests/
dev f81a33e this branch (dc723d8)
pytest 2877 passed, 6 failed, 10 skipped, 1 xfailed 2905 passed, 6 failed, 10 skipped, 1 xfailed
the new file, against each tree's src/ 24 failed, 4 passed 28 passed
the new file plus test_object_property_threshold.py 26 failed, 36 passed 62 passed

The 4 that pass on dev pin behaviour this must keep or that dev gets right by not carrying anything: the array items case, 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 in TestRealisticDeepNesting and test_integration in test_realistic_deep_nesting.py, all AttributeError: module 'signal' has no attribute 'SIGALRM'. Linux CI runs them.

uv run ruff check . gives the same 16 findings on both trees, all in examples/notebooks/*.ipynb and examples/scripts/llm_comparator_demo.py. On the three changed Python files ruff check passes. ruff format --check passes for the importer and the new test file, and flags test_object_property_threshold.py for one docstring at line 448 that it also flags on dev; this PR does not touch that line. mkdocs build gives the same 9 warnings on both trees.

Reviewers

@sromoam

Checklist

  • Code follows the project's coding standards
  • Self-review of code completed
  • Documentation updated (if applicable)
  • CHANGELOG.md entry added under [Unreleased], or not needed because
    nothing user-visible changed (see RELEASING.md)
  • Tests added/updated for new functionality
  • All CI checks are passing
  • Ready for review

Additional Notes

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

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
@Thanatos9404
Thanatos9404 requested a review from sromoam as a code owner October 16, 2026 11:31
@github-actions

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-10-16T15:47:40+00:00
  • Time since scan: 3 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-10-16T15:44:23+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 3 0 0 5822 0 3 FAILED 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 1 0 0 0 0 1 SKIPPED 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)

Top 2 Hotspots

Files with the highest number of security findings:

Finding Count File Location
2 tests/comparators/test_anls_leaf_semantics.py
2 tests/structured_object_evaluator/test_rollup_node_semantics.py

Detailed Findings

Show 4 actionable findings

Finding 1: SECRET-HEX-HIGH-ENTROPY-STRING

  • Severity: HIGH
  • Scanner: detect-secrets
  • Rule ID: SECRET-HEX-HIGH-ENTROPY-STRING
  • Location: tests/comparators/test_anls_leaf_semantics.py:89

Description:
Secret of type 'Hex High Entropy String' detected in file 'tests/comparators/test_anls_leaf_semantics.py' at line 89

Code Snippet:

Secret of type Hex High Entropy String detected

Finding 2: B108

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B108
  • Location: tests/comparators/test_anls_leaf_semantics.py:210-212

Description:
Probable insecure usage of temp file/directory.

Code Snippet:

uuid.UUID(int=1),
            pathlib.Path("/tmp/x"),
            b"bytes",

Finding 3: B307

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B307
  • Location: tests/structured_object_evaluator/test_rollup_node_semantics.py:1362-1368

Description:
Use of possibly insecure function - consider using safer ast.literal_eval.

Code Snippet:

def published_label(node: dict, section: str, object_lists: set) -> str:
            counts_objects = eval(  # noqa: S307
                cond.group(1),
                {},
                {"data": node, "section": section, "OBJECT_LISTS": object_lists},
            )
            return eval(unit.group(1), {}, {"counts_objects": counts_objects})  # noqa: S307

Finding 4: B307

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B307
  • Location: tests/structured_object_evaluator/test_rollup_node_semantics.py:1367-1369

Description:
Use of possibly insecure function - consider using safer ast.literal_eval.

Code Snippet:

)
            return eval(unit.group(1), {}, {"counts_objects": counts_objects})  # noqa: S307

Report generated by Automated Security Helper (ASH) at 2026-10-16T15:47:42+00:00

@sromoam

sromoam commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

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 dev turned up exactly that:

  • a definition reached through items or a root $ref passes the check, and its key is then never read;
  • a definition that is an object through a $ref alias or an anyOf-nullable wrapper now has its object-level key rejected, though that schema imported on dev;
  • null arms other than {"type": "null"} (such as {"const": null}) stop the carry, so the key is dropped silently.

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 $ref), so there's one rule and nothing is dropped silently. It also fixes #349 part A in the same code.

If you're up for another one in this area, #349 parts B and C are open and unclaimed:

  • re-importing to_json_schema() output fails for several nested shapes;
  • a Union field exports as "string".

The List[Dict] row is already handled in #405, so skip that one. You know the importer side of this now, which is most of what B and C need. Separately, once #406 merges, #398 will need a small rescope: #406 stops calling classify_field_for_confusion_matrix, so that function can be deleted as part of #395 rather than fixed. Thanks again!

@sromoam sromoam closed this Oct 16, 2026
@Thanatos9404

Copy link
Copy Markdown
Contributor Author

Thanks @sromoam, that makes sense: one rule that raises is easier to keep right than a carry for every way a definition can be referenced, and the cases you list are exactly where the carry got fragile. I'll take #349 parts B and C, and I'll rescope #398 once #406 is in.

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

2 participants