Skip to content

fix(310): score a non-numeric string in a numeric field instead of raising - #626

Open
nursnaaz wants to merge 9 commits into
awslabs:devfrom
nursnaaz:fix/310-non-numeric-in-numeric-field
Open

nursnaaz wants to merge 9 commits into
awslabs:devfrom
nursnaaz:fix/310-non-numeric-in-numeric-field

Conversation

@nursnaaz

Copy link
Copy Markdown
Collaborator

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 by from_json_schema() or model_from_json() now gets scored instead of raising ValidationError at model construction. Stickler keeps such a string as written, and the field's comparator scores it. NumericComparator scores "N/A" against 1234.5 as 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 "١٢٥٠" against 1250 scores 1.0). "" counts as absent, so "" against "" or None scores 1.0.

This is narrower than what I proposed in the issue. My comment listed a hand-written StructuredModel field 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:

  • Hand-written classes are left alone. Changing the validation of a class users write themselves is a behaviour change for anyone who relies on it rejecting "N/A". A hand-written class can opt in in a follow-up, through the same validator, if you want that.
  • A validator instead of widening. It keeps valid input, FieldInfo.annotation and exports identical; widening would not. With Union[float, str], pydantic's smart union stores "1234.50" as the string rather than as 1234.5, while today "1234.50" coerces, as MohammedAlkindi noted in the issue. Widening would also change the field_info.annotation that many readers in the package use for the comparator, nullability and export shape.

Changes Made

  • New module models/scoreable_number.py.
    • It adds a wrap validator to the numeric fields of a generated class (int, float and their Optional forms). A value pydantic accepts is stored as before. A string pydantic rejects is stored as written. Any other rejected value still raises.
    • Those fields carry a serializer in FieldInfo.metadata, all in pydantic-core. It's a union, in this order, of the field's own numeric schema, str, and for a float or Optional[float] field an int arm that converts to float in JSON modes. The order matters: the int arm's serializer is a plain float function, which pydantic-core calls on any value that reaches it, and float() reads Unicode digits. Ahead of str, it would dump a kept "١٢٥٠" as 1250.0.
      • A validated number dumps as before in model_dump(), model_dump(mode="json") and model_dump_json(), including inf, nan, -0.0 and large integers.

      • So does an int or bool that fits a float and reached a float field without validation, through assignment, model_copy(update=) or model_construct(): 100 dumps as 100.0 in JSON modes and 100 in 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:

        • A Decimal dumps as a float (1.5), where a plain float field gives its string ("1.5") with a warning.
        • An int too large for a float (10**400) is returned with a warning, where a plain float field raises OverflowError.

        model_dump() matches in both cases. model_dump_json() matches for the Decimal.

        A third difference is benign: a string set without validation now dumps without the serializer warning that a plain numeric field gives.

  • FieldInfo.annotation stays float or int. So the comparator choice and nullability are unchanged. FieldInfo.metadata now holds the serializer marker, and rebuild_annotation() returns Annotated[float, <marker>]. I compared to_json_schema(), to_stickler_config() and model_json_schema() (validation and serialization modes) byte for byte against dev, for both builders.
  • ModelFactory.create_model_from_fields() gains a keyword-only scoreable_numbers flag, off by default. The two schema build sites (root and nested) and create_model_from_json() turn it on.
  • Docs:
    • A new section in dynamic-models.md, "A string a numeric field cannot read". It also covers the integer vs number difference, strict validation, ground truths, and the limits.
    • An updated note under NumericComparator in the comparator guide.
    • The models README.
    • A CHANGELOG entry under [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:

  • A class written by hand, from_pydantic(), and create_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.
  • Still raises: an element of a numeric array, a union of two numeric types ({"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 as 12.5 in an integer field (the string "12.5" is kept).
  • Strict validation, including 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.
  • A subclass that redeclares a numeric field (amount: float) inherits the validator but not the serializer, so it keeps "N/A" but model_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:

Operation dev This PR
Building the instances 12 ms 21–22 ms
model_dump() 6–7 ms 7–8 ms
model_dump_json() 7–8 ms 9–10 ms
compare_with() on 100 pairs 9–10 ms 9–10 ms

An 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.toml allows 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:

    • all four builders (schema number and integer, config float and int);
    • nested objects, lists of objects, every nullable spelling, and constrained numbers;
    • opting in through create_model_from_fields;
    • model_dump round trips with warnings turned into errors;
    • dump parity with a strict class for inf, nan, -0.0 and large integers, in model_dump(), model_dump(mode="json") and model_dump_json();
    • evaluate() on inf and nan, which dumps with mode="json";
    • an int, bool or large integer set by assignment, model_copy(update=) or model_construct(), in required and Optional fields, with warnings as errors, against a strict class in all three dump modes, and both differences above;
    • kept strings, lax ("١٢٥٠", "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 a model_validate_json round trip;
    • model_json_schema() parity in both modes;
    • valid-input parity;
    • ground truths the comparator can and cannot read, a mixed numeric enum, the integer vs number difference, 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:

    • the validator keeping any type, keeping nothing, or also keeping bytes;
    • the serializer:
      • by value (it turns inf into None in JSON mode), numeric-only, not overridden, or not applied;
      • typed -> Any (which exports {}), or a plain function returning the value;
      • without the int arm, with it only on a bare float (not Optional[float]), with it on int fields too, converting in every mode, or not converting;
      • with the int arm ahead of str, as in the previous revision (it dumps a kept "١٢٥٠" as 1250.0);
    • bool counted as numeric;
    • no Optional unwrap when detecting numeric fields, and no Annotated unwrap in either position;
    • any union arm counting as numeric;
    • int-only and float-only checks;
    • each of the three build sites switched off;
    • the flag ignored, or on by default.

    The one survivor puts str ahead 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 the int arm, a plain function, has to stay behind str, 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 and evaluate() all run without error or warning.

  • Full suite: I ran CI's own commands, uv sync --extra llm --extra bert --frozen and then uv run coverage run -m pytest -v -s, on Python 3.12, for this branch and for dev (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, and ruff check . passes. The figures above were measured before the rebase; the increase is tests added to dev since.

  • Lint: ruff check . and docs/check_links.py pass. ruff format --check passes on the new files. The three existing source files I touched have the same ruff format drift as on dev, and no new drift.

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

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

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-12-05T07:41:06+00:00
  • Time since scan: 4 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-12-05T07:36:42+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 8318 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 7 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-12-05T07:41:07+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.

✅ LGTM!

@nursnaaz
nursnaaz force-pushed the fix/310-non-numeric-in-numeric-field branch from ab004a7 to 1e7aa2d Compare November 27, 2026 19:13

@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!

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.

@digalaviz

Copy link
Copy Markdown
Contributor

This conflicts with dev now, only in structured_object_evaluator/models/README.md. Could you bring dev in? It's approved, so it should be ready once CI is green.

@nursnaaz
nursnaaz force-pushed the fix/310-non-numeric-in-numeric-field branch from 1e7aa2d to da5f590 Compare November 30, 2026 09:45

@sromoam sromoam 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.

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

  1. 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, and model_from_json() and from_json_schema() build with base_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 example Child(amount="N/A", qty="n/a") for both builders.

Smaller

  1. The new docs section describes the change rather than the behaviour (dynamic-models.md:264-270 and :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

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.

For the counter below (Must fix 1).

Suggested change
from typing import Annotated, Any, Dict, List
import itertools
from typing import Annotated, Any, Dict, List

Comment on lines +139 to +145
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
),
}

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.

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

Suggested change
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)}

Comment thread docs/docs/Advanced/dynamic-models.md Outdated
Comment on lines +264 to +270
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.

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.

Says what happens without "as before", "still" or "unchanged", and splits the strict round-trip sentence (Smaller 1).

Suggested change
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.

Comment thread docs/docs/Advanced/dynamic-models.md Outdated
Comment on lines +281 to +282
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

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.

Smaller 1.

Suggested change
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.
@nursnaaz
nursnaaz force-pushed the fix/310-non-numeric-in-numeric-field branch from da5f590 to e2e0a35 Compare December 3, 2026 17:35
@nursnaaz

nursnaaz commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @sromoam, good catch on the inherited fields. Pushed e2e0a35 on top of a rebase onto current dev:

  • Validator name per class: took your counter, so a class built on a generated class adds its own validator instead of replacing its parent's. Your repro now keeps "N/A" on the inherited amount with both model_from_json() and from_json_schema().
  • Tests: Child(amount="N/A", qty="n/a") for both builders, which also checks the inherited field scores 0.0, and three levels of inheritance under -W error. All four fail with a shared validator name.
  • Docs: took both suggestions in dynamic-models.md, so the section describes the behaviour rather than release history.

Full suite: 7748 passed, 13 skipped, 1 xfailed; ruff check . and docs/check_links.py pass. No rush given the 1.1.0 freeze.

@nursnaaz
nursnaaz requested a review from sromoam December 3, 2026 18:51

@sromoam sromoam 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.

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

  1. A rebuilt Score decision field keeps an answer it should reject (scoreable_number.py:61). 1.1.0's Score fields import as Optional[int], so numeric_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 raises ValidationError when 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 whose FieldInfo carries a decision spec (field_decision_spec() in stickler.decisions.primitives) fixes it. With that, both rebuilt classes raise again, and your 332 tests and tests/decisions pass. Please add a test for both builders, and say in dynamic-models.md that a Score field keeps its own validation.

  2. 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 bring dev in and move it under ## [Unreleased], in a new ### Fixed.

Smaller

  1. scoreable_numbers is new public API in a patch (model_factory.py:270, the CHANGELOG's last sentence and dynamic-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 just ModelFactory.create_model_from_fields().
  2. An em dash in models/README.md:35. A colon works, as the threshold_rule.py entry has.

@sromoam sromoam added this to the 1.1.1 milestone Dec 4, 2026
…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.
@nursnaaz

nursnaaz commented Dec 5, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @sromoam, all four are in.

Must fix

  1. Score fields. A decision field is now left out in two places.

    • When the class is built, numeric_field_names() skips a field whose FieldInfo carries a decision spec, so the field gets neither the fallback validator nor the serializer.
    • When a value is validated, the fallback keeps a string only while the class still declares the field as a plain number with no decision spec. That covers a subclass that redeclares an inherited numeric field as a Score, or as a list or any other type, since the validator is inherited by name.

    Your model_from_questions() repro now raises on "high", "5" and "N/A" with both builders, as the original does. A rebuilt Score accepts each level and None. The new tests cover, with both builders wherever a class is rebuilt:

    • that repro;
    • a top-level Score, a Score in a nested model and a Score in a list of models;
    • a numeric field beside a Score field, which still keeps "N/A";
    • a subclass that redeclares a field as a Score (both as a class and through create_model_from_fields()), or as a list, a dict or a bool.

    Removing either check makes tests fail. dynamic-models.md and the CHANGELOG entry now say that a decision field, or a field a subclass redeclares as anything other than a number, keeps its own validation.

  2. CHANGELOG. I merged dev (8d7cc65) and moved the entry under ## [Unreleased]. That section already had a ### Fixed from fix(462): give every threshold verdict one reason text #696, so the entry goes there. The entry now opens with an upgrade note for the strict-mode change: under strict=True a numeric string such as "1234.5" is kept as a string.

Smaller

  1. The flag is now _scoreable_numbers and the CHANGELOG sentence about it is gone. The docs now say only that a class built by ModelFactory.create_model_from_fields() on a base of your own keeps pydantic's validation.
  2. The em dash in models/README.md is now a colon.

One more thing I found while testing. A numpy.int64 set on an int field without validation (assignment, model_copy(update=) or model_construct()) could no longer be written by model_dump_json(). The serializer's union fell back to type inference, which can't write a numpy scalar to JSON. Its last arm now converts a value the way the field's own serializer does: through __index__ for an int field and float() for a float field. Anything else it declines, so that value falls back as before.

I compared the dumps against dev for:

  • ints, bools, floats, big ints, -0.0, inf, nan, None;
  • lists, dicts, bytes;
  • Decimal (including NaN and Infinity) and Fraction;
  • IntEnum and int/float subclasses;
  • numpy ints, floats, bools and arrays.

Each value went into an int, a float, an optional int and an optional float field, by assignment and by model_construct(). Each was then dumped with model_dump(), model_dump(mode="json") and model_dump_json(). model_dump() and model_dump_json() match dev exactly. Two things differ:

  • A kept string dumps without the warning.
  • In model_dump(mode="json") only, some values dev raised or warned on are now written as the number model_dump_json() already wrote. These are a Decimal, a Fraction or a numpy value in a float field, and a numpy integer in an int field.

The CHANGELOG entry says so, and a test pins that rule against a hand-written class. model_json_schema() is unchanged in both modes.

Testing on the merge

  • Full suite: 7877 passed, 13 skipped, 1 xfailed. ruff check, docs/check_links.py and tests/test_docs_build.py pass.
  • This file, tests/decisions and tests/integrations also pass on Python 3.10, 3.11, 3.13 and 3.14.
  • Validation is slower on numeric-heavy documents: 300 invoices with 90 numeric fields each take about 6 ms more. Comparing those same documents takes about 2.2 s, so the end-to-end difference is within noise.

This branch has not been deployed

No deployments
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.

[BUG]: a non-numeric string in a numeric field aborts the run instead of scoring 0.0

4 participants