Repository navigation
Conversation
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-12-05T07:41:07+00:00 |
ab004a7 to
1e7aa2d
Compare
vawsgit
left a comment
There was a problem hiding this comment.
✅ LGTM!
Re-approval on 1e7aa2d8. The change from ab004a7c is a rebase onto dev 13a21ba. Per file, the patches are identical in 8 of 9 files, including all code, tests and docs. CHANGELOG.md differs only in its context lines after the rebase, plus a closing period on the #310 entry.
The merge is clean (git merge-tree, and GitHub reports MERGEABLE, CLEAN). Full suite on 1e7aa2d8, with PYTHONPATH pinned to its src: 6970 passed, 3 skipped, 1 xfailed, 0 failed. dev 13a21ba has 6642 passed. CI passed on 1e7aa2d8.
|
This conflicts with |
1e7aa2d to
da5f590
Compare
sromoam
left a comment
There was a problem hiding this comment.
Thanks @nursnaaz, this is careful work, and the description made it easy to check. On da5f590a I reproduced the ValidationError on dev and confirmed "N/A" now builds and scores 0.0 through both builders, including nested objects, arrays of objects, $ref and allOf roots and nullable fields. The new file fails 97 of its 328 tests on dev and passes them all here, to_json_schema(), to_stickler_config() and model_json_schema() match dev byte for byte on those shapes, and the full suite passes merged with current dev. The push since vawsgit's approval is only the rebase (every file's patch is identical), and it clears the README conflict Diego raised. Two things the earlier rounds missed:
Must fix
-
A class built on a generated class loses the fallback on the fields it inherits (
scoreable_number.py:142). Every generated class registers its validator under the same name,_keep_unparseable_numeric_string, andmodel_from_json()andfrom_json_schema()build withbase_class=cls. pydantic keys inherited validators by name, so the child's validator, which lists only the child's own numeric fields, replaces the parent's.Base = StructuredModel.from_json_schema({"type": "object", "properties": {"amount": {"type": "number"}}}) Child = Base.model_from_json({"model_name": "Child", "fields": {"qty": {"type": "int", "comparator": "NumericComparator"}}}) Child(amount=1, qty="N/A") # kept Child(amount="N/A", qty=1) # ValidationError: Input should be a valid number
Base.from_json_schema(...)fails the same way. A validator name per class fixes it (suggestions inline). With that change both builders keep the string on inherited fields, three levels of inheritance work under-W error, and your 328 tests still pass. Please add a test for it, for exampleChild(amount="N/A", qty="n/a")for both builders.
Smaller
- The new docs section describes the change rather than the behaviour (
dynamic-models.md:264-270and:281). "stored exactly as before", "still becomes", "stays ... unchanged" and "used to fail when it was built; it is now kept" are release history, which belongs in the CHANGELOG. Suggestions inline; the one at 264 also splits the strict round-trip sentence in two.
One heads-up: we're not merging anything outside the 1.1.0 milestone until 1.1.0 lands, so this will wait until after that even once it's ready.
| choose. | ||
| """ | ||
|
|
||
| from typing import Annotated, Any, Dict, List |
There was a problem hiding this comment.
For the counter below (Must fix 1).
| from typing import Annotated, Any, Dict, List | |
| import itertools | |
| from typing import Annotated, Any, Dict, List |
| def scoreable_number_validators(names: List[str]) -> Dict[str, Any]: | ||
| """The ``__validators__`` that keep a non-numeric string in ``names``.""" | ||
| return { | ||
| "_keep_unparseable_numeric_string": field_validator(*names, mode="wrap")( | ||
| _keep_unparseable_string | ||
| ), | ||
| } |
There was a problem hiding this comment.
A name per class, so a class built on a generated class adds its own validator instead of replacing the parent's (Must fix 1).
| def scoreable_number_validators(names: List[str]) -> Dict[str, Any]: | |
| """The ``__validators__`` that keep a non-numeric string in ``names``.""" | |
| return { | |
| "_keep_unparseable_numeric_string": field_validator(*names, mode="wrap")( | |
| _keep_unparseable_string | |
| ), | |
| } | |
| # One name per generated class: pydantic keys inherited validators by name, so a | |
| # shared name would let a class built on a generated class replace the | |
| # validator that covers the fields it inherits. | |
| _VALIDATOR_IDS = itertools.count() | |
| def scoreable_number_validators(names: List[str]) -> Dict[str, Any]: | |
| """The ``__validators__`` that keep a non-numeric string in ``names``.""" | |
| name = f"_keep_unparseable_numeric_string_{next(_VALIDATOR_IDS)}" | |
| return {name: field_validator(*names, mode="wrap")(_keep_unparseable_string)} |
| A value the numeric type accepts is stored exactly as before, so `"1234.50"` still becomes | ||
| `1234.5`. `model_dump()`, `model_dump(mode="json")` and `model_dump_json()` return a kept | ||
| string as the string, and validating the dump the way the string was kept builds the same | ||
| instance. That means lax validation, or strict validation for a numeric string such as | ||
| `"1234.5"` that only strict validation keeps; lax validation reads that one as a number. The field's `FieldInfo.annotation` stays `float` or `int`, so | ||
| `to_json_schema()`, `model_json_schema()` and the comparator are unchanged; its | ||
| `FieldInfo.metadata` holds the serializer that dumps a kept string as a string. |
There was a problem hiding this comment.
Says what happens without "as before", "still" or "unchanged", and splits the strict round-trip sentence (Smaller 1).
| A value the numeric type accepts is stored exactly as before, so `"1234.50"` still becomes | |
| `1234.5`. `model_dump()`, `model_dump(mode="json")` and `model_dump_json()` return a kept | |
| string as the string, and validating the dump the way the string was kept builds the same | |
| instance. That means lax validation, or strict validation for a numeric string such as | |
| `"1234.5"` that only strict validation keeps; lax validation reads that one as a number. The field's `FieldInfo.annotation` stays `float` or `int`, so | |
| `to_json_schema()`, `model_json_schema()` and the comparator are unchanged; its | |
| `FieldInfo.metadata` holds the serializer that dumps a kept string as a string. | |
| A value the numeric type accepts is stored as that number, so `"1234.50"` becomes `1234.5`. | |
| `model_dump()`, `model_dump(mode="json")` and `model_dump_json()` return a kept string as the | |
| string, and validating the dump again builds the same instance. A numeric string that only strict | |
| validation keeps, such as `"1234.5"`, needs strict validation again, since lax validation reads it | |
| as a number. The field's `FieldInfo.annotation` is `float` or `int` even when it holds a string, | |
| so `to_json_schema()` and `model_json_schema()` describe a number and the comparator is chosen | |
| as for any number field; its `FieldInfo.metadata` holds the serializer that dumps a kept string | |
| as a string. |
| The same applies to a ground truth. One holding `"N/A"` used to fail when it was built; it is now | ||
| kept. A ground truth the comparator cannot read, such as `"N/A"`, scores 0.0 against every |
There was a problem hiding this comment.
Smaller 1.
| The same applies to a ground truth. One holding `"N/A"` used to fail when it was built; it is now | |
| kept. A ground truth the comparator cannot read, such as `"N/A"`, scores 0.0 against every | |
| The same applies to a ground truth: one holding `"N/A"` builds and keeps the string. A ground | |
| truth the comparator cannot read, such as `"N/A"`, scores 0.0 against every |
…ising A prediction holding "N/A", "" or "see attached" in a number or integer property of from_json_schema(), or a float or int field of model_from_json(), failed model construction, so a bulk run stopped at that document. The generated classes now keep such a string as written, and the field's comparator scores it: NumericComparator scores "N/A" as 0.0 and reads "١٢٥٠" as 1250. A wrap validator keeps only strings the numeric type rejects, so a value it accepts is stored exactly as before. FieldInfo.annotation stays float or int, so comparator choice and nullability are unchanged, and to_json_schema(), to_stickler_config() and model_json_schema() in both modes match the previous output. FieldInfo.metadata now carries a serializer: a union of the field's own numeric schema, then str, then for a float or Optional[float] field an int arm that converts to float in JSON modes. A validated number dumps as before in every mode, inf and nan included, and so does an int or bool that fits a float and was set without validation (assignment, model_copy(update=), model_construct()). A kept string dumps as the string in every mode without a warning. For values set without validation, two differences remain for numbers, both under model_dump(mode="json"): a Decimal dumps as a float rather than its string, and an int too large for a float is returned with a warning instead of raising OverflowError. A string set without validation now dumps without the serializer warning it used to give. Hand-written classes, from_pydantic() and create_model_from_fields() keep pydantic's validation; the last gains an opt-in scoreable_numbers flag. Closes awslabs#310
…ed class Every generated class registered its validator under one name, and pydantic keys inherited validators by name, so a class built on a generated class replaced the validator covering the fields it inherits. Each class now gets its own name. Tests cover both builders and three levels of inheritance. Docs describe the behaviour without release history.
da5f590 to
e2e0a35
Compare
|
Thanks @sromoam, good catch on the inherited fields. Pushed
Full suite: 7748 passed, 13 skipped, 1 xfailed; |
sromoam
left a comment
There was a problem hiding this comment.
Thanks @nursnaaz, the validator name per class does it, and both docs suggestions are in. I checked e2e0a354 merged with dev 9680269 (the 1.1.0 release). My repro now keeps "N/A" on the inherited amount with both builders, and three levels keep every fallback. The new file has 332 tests: 101 fail on dev and all pass here, and the four inheritance tests fail again with a shared validator name. "N/A", "١٢٥٠", "", strict mode, the integer cases, the dumps, model_json_schema() and a bulk run all behave as the docs say. Full suite on the merge: 7811 passed, 3 skipped, 1 xfailed; ruff and docs/check_links.py pass. One thing came in with 1.1.0:
Must fix
-
A rebuilt Score decision field keeps an answer it should reject (
scoreable_number.py:61). 1.1.0'sScorefields import asOptional[int], sonumeric_field_names()picks them up, and the wrap validator keeps any string the level check rejects. The decision models guide says a value that is not one of the question's answers raisesValidationErrorwhen the model is built, and the original still does:Triage = model_from_questions({"severity": {"type": "score", "criteria": ["low", "medium", "high"]}}) Rebuilt = StructuredModel.from_json_schema(Triage.to_json_schema()) Triage(severity="high") # ValidationError Rebuilt(severity="high") # builds, severity == "high"; "5" and "N/A" too
model_from_json(Triage.to_stickler_config())does the same. In bulk the document is then scored, and the decision accumulator drops it with "A Score gold value must be a level number". Skipping a field whoseFieldInfocarries a decision spec (field_decision_spec()instickler.decisions.primitives) fixes it. With that, both rebuilt classes raise again, and your 332 tests andtests/decisionspass. Please add a test for both builders, and say indynamic-models.mdthat a Score field keeps its own validation. -
The CHANGELOG entry lands in 1.1.0. The branch predates the release, so the entry merges cleanly into
## [1.1.0] - 2026-12-04, under### Fixed. Please bringdevin and move it under## [Unreleased], in a new### Fixed.
Smaller
scoreable_numbersis new public API in a patch (model_factory.py:270, the CHANGELOG's last sentence anddynamic-models.md). This ships in 1.1.1, and RELEASING.md keeps new public API out of a patch. Only the importer passes it, so a private name (_scoreable_numbers) keeps it internal. The CHANGELOG sentence can then go, and the docs can name justModelFactory.create_model_from_fields().- An em dash in
models/README.md:35. A colon works, as thethreshold_rule.pyentry has.
…nternal A rebuilt Score field is typed Optional[int], so the numeric fallback picked it up and kept answers the original rejects. Decision fields are now left out. The importer's flag on create_model_from_fields() is private, since a patch release adds no public API, and the CHANGELOG entry moves to Unreleased.
The fallback validator is inherited by name, so a subclass that redeclared an inherited numeric field as a Score kept a string there. Pin the guide's model_from_questions() route and the build-time skip with tests.
…d's validation A numpy integer set on an int field without validation could no longer be written by model_dump_json(): the serializer's union fell back to type inference. Its last arm now converts a number as the field's own serializer does and declines anything else, so every value but a kept string dumps as before. The fallback also keeps a string only while the field is still a plain number, so a subclass that retypes it keeps that type's validation. Wording in the CHANGELOG, docs and docstrings is tightened, with an upgrade note for the strict-mode change.
…wording numpy.bool_ and numpy arrays set on a float field without validation broke model_dump_json(); the float arm now converts whatever float() accepts, bar strings and bytes. The CHANGELOG entry leads with its upgrade note and names the JSON-mode change, and create_model_from_fields() is described precisely.
…rializer does On numpy releases where numpy.bool_ has __index__, model_dump_json() writes it in an int field; the int arm now converts what operator.index() accepts. The dump-parity test checks that rule rather than a fixed list.
|
Thanks @sromoam, all four are in. Must fix
Smaller
One more thing I found while testing. A I compared the dumps against
Each value went into an
The CHANGELOG entry says so, and a test pins that rule against a hand-written class. Testing on the merge
|
Pull Request
Issue Reference
Closes #310
Description of Changes
A prediction holding
"N/A",""or"see attached"in a numeric field of a class built byfrom_json_schema()ormodel_from_json()now gets scored instead of raisingValidationErrorat model construction. Stickler keeps such a string as written, and the field's comparator scores it.NumericComparatorscores"N/A"against1234.5as 0.0, and reads"١٢٥٠"as 1250. A ground truth holding such a string now builds too. One the comparator cannot read, such as"N/A", scores 0.0 against every prediction; one it can read still matches ("$1,250"or"١٢٥٠"against1250scores 1.0).""counts as absent, so""against""orNonescores 1.0.This is narrower than what I proposed in the issue. My comment listed a hand-written
StructuredModelfield among the paths to fix, and said "widening". This PR covers only the classes Stickler builds, and it uses a validator instead of widening the annotation:"N/A". A hand-written class can opt in in a follow-up, through the same validator, if you want that.FieldInfo.annotationand exports identical; widening would not. WithUnion[float, str], pydantic's smart union stores"1234.50"as the string rather than as1234.5, while today"1234.50"coerces, as MohammedAlkindi noted in the issue. Widening would also change thefield_info.annotationthat many readers in the package use for the comparator, nullability and export shape.Changes Made
models/scoreable_number.py.int,floatand theirOptionalforms). A value pydantic accepts is stored as before. A string pydantic rejects is stored as written. Any other rejected value still raises.FieldInfo.metadata, all in pydantic-core. It's a union, in this order, of the field's own numeric schema,str, and for afloatorOptional[float]field anintarm that converts tofloatin JSON modes. The order matters: theintarm's serializer is a plainfloatfunction, which pydantic-core calls on any value that reaches it, andfloat()reads Unicode digits. Ahead ofstr, it would dump a kept"١٢٥٠"as1250.0.A validated number dumps as before in
model_dump(),model_dump(mode="json")andmodel_dump_json(), includinginf,nan,-0.0and large integers.So does an
intorboolthat fits a float and reached afloatfield without validation, through assignment,model_copy(update=)ormodel_construct():100dumps as100.0in JSON modes and100in Python mode, with no warning.A kept string dumps as the string in all three modes, without pydantic's "expected a number" warning. That includes
"١٢٥٠"and"1٢", and strict-kept numeric strings such as"1234.5","nan"or"infinity". Validating the dump the way the string was kept builds the same instance; lax validation reads a strict-kept"1234.5"as a number.For values set without validation, two differences remain for numbers, both under
model_dump(mode="json")only:Decimaldumps as a float (1.5), where a plain float field gives its string ("1.5") with a warning.10**400) is returned with a warning, where a plain float field raisesOverflowError.model_dump()matches in both cases.model_dump_json()matches for theDecimal.A third difference is benign: a string set without validation now dumps without the serializer warning that a plain numeric field gives.
FieldInfo.annotationstaysfloatorint. So the comparator choice and nullability are unchanged.FieldInfo.metadatanow holds the serializer marker, andrebuild_annotation()returnsAnnotated[float, <marker>]. I comparedto_json_schema(),to_stickler_config()andmodel_json_schema()(validation and serialization modes) byte for byte againstdev, for both builders.ModelFactory.create_model_from_fields()gains a keyword-onlyscoreable_numbersflag, off by default. The two schema build sites (root and nested) andcreate_model_from_json()turn it on.dynamic-models.md, "A string a numeric field cannot read". It also covers theintegervsnumberdifference, strict validation, ground truths, and the limits.NumericComparatorin the comparator guide.[Unreleased].Why These Changes Are Needed
This follows the direction in the issue, scoped as above. Like #285, it keeps the parsed type for choosing the comparator, but a malformed prediction is no longer rejected before scoring.
Out of scope, and documented:
from_pydantic(), andcreate_model_from_fields()without the flag keep pydantic's validation.stickler.evaluate()on the caller's pydantic instances: the caller's class validates the value before Stickler sees it.{"type": ["number", "integer"]}), a numeric enum mixing integers and decimals ({"type": "number", "enum": [1, 2.5]}), a union of a number with another non-string type, and a non-integer number such as12.5in anintegerfield (the string"12.5"is kept).model_validate_json(..., strict=True), rejects a numeric string, so"1234.5"is now kept as a string there rather than raising. That follows from keeping any string the numeric type rejects.amount: float) inherits the validator but not the serializer, so it keeps"N/A"butmodel_dump()warns.What it costs. I measured 5,000 instances of a model with 10 numeric fields on Python 3.12 and pydantic 2.12.5, best of 7 runs, two runs each, against
dev:devmodel_dump()model_dump_json()compare_with()on 100 pairsAn earlier run on a busier machine measured building at 13–16 ms against 25–28 ms. The independent reviewer measured building at 23–24.5 ms against 12–14 ms on their machine. Most of the build cost is the Python wrap validator: about 2 µs per 10-field instance, or 0.2 µs per numeric field. Moving it into pydantic-core, as a left-to-right union of the original schema and a strict string, measured the same as plain pydantic (7.8 ms against 7.7 ms on a bare model). The trade-off is that a list or dict in a numeric field would then report the union's two errors instead of the original one. I kept the validator; happy to switch if you prefer.
Pydantic versions. CI pins pydantic 2.12.5, which I tested; the reviewer also ran 2.13.5.
pyproject.tomlallows 2.11, which is untested.Testing
Unit tests added/updated
Integration tests added/updated
Manual testing completed
All existing tests pass
New file
tests/structured_object_evaluator/test_non_numeric_in_numeric_field.py. It covers:numberandinteger, configfloatandint);create_model_from_fields;model_dumpround trips with warnings turned into errors;inf,nan,-0.0and large integers, inmodel_dump(),model_dump(mode="json")andmodel_dump_json();evaluate()oninfandnan, which dumps withmode="json";int,boolor large integer set by assignment,model_copy(update=)ormodel_construct(), in required andOptionalfields, with warnings as errors, against a strict class in all three dump modes, and both differences above;"١٢٥٠","1٢","N/A") and strict ("1234.5","12"," 12 ","1_000.5","nan","infinity"), in number, config-float and integer fields: the string in all three dump modes with warnings as errors, and amodel_validate_jsonround trip;model_json_schema()parity in both modes;integervsnumberdifference, strict validation (including JSON),bytes, a boolean field, and the limits above.On
dev, 97 of its 328 tests fail (every repro case) and the other 231 pass (the parity and limit tests). With the previous serializer order, 16 of the 27 kept-string tests fail.Mutation checks: 28 targeted source mutations. 27 are killed by at least one test:
bytes;infintoNonein JSON mode), numeric-only, not overridden, or not applied;-> Any(which exports{}), or a plain function returning the value;intarm, with it only on a barefloat(notOptional[float]), with it onintfields too, converting in every mode, or not converting;intarm ahead ofstr, as in the previous revision (it dumps a kept"١٢٥٠"as1250.0);boolcounted as numeric;Optionalunwrap when detecting numeric fields, and noAnnotatedunwrap in either position;int-only andfloat-only checks;The one survivor puts
strahead of the numeric arm as well,[str, numeric, int]. It is equivalent: both of those arms type-check, so a number still reaches the numeric serializer and a string the string one. Only theintarm, a plain function, has to stay behindstr, and that order is pinned by the killed mutant above.Reporting paths with kept strings:
compare_with()under every flag combination,from_json(..., process_rich_values=True),BulkStructuredModelEvaluator, the HTML report andevaluate()all run without error or warning.Full suite: I ran CI's own commands,
uv sync --extra llm --extra bert --frozenand thenuv run coverage run -m pytest -v -s, on Python 3.12, for this branch and fordev(57f9f3b). The branch gives 6,921 passed against 6,593, with 3 skipped and 1 xfailed on both. That is exactly the 328 new tests: every other test has the same outcome, and none fail. On this revision the same commands on Python 3.10 give 6,917 passed, 7 skipped, 1 xfailed, and on 3.14 6,921 passed, 3 skipped, 1 xfailed, with no failures.After rebasing onto the latest
dev(6657873): the full suite on Python 3.12 gives 6,936 passed, 3 skipped, 1 xfailed, andruff check .passes. The figures above were measured before the rebase; the increase is tests added todevsince.Lint:
ruff check .anddocs/check_links.pypass.ruff format --checkpasses on the new files. The three existing source files I touched have the sameruff formatdrift as ondev, and no new drift.Checklist
CHANGELOG.mdentry added under[Unreleased], or not needed becausenothing user-visible changed (see RELEASING.md)
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.