Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
e364b7a
fix(importers): resolve unstated threshold and clip as the Python pat…
sromoam Oct 15, 2026
adbda67
fix(importers): credit a zero threshold to the comparator only when i…
sromoam Oct 16, 2026
3637981
Merge origin/dev into fix/334-348-importer-defaults
sromoam Oct 28, 2026
530e77f
test: pin the free-form clip default from #334 in the extension refer…
sromoam Oct 28, 2026
ede3216
Merge remote-tracking branch 'origin/dev' into m408
sromoam Oct 29, 2026
60703e0
fix(334): name an adopted comparator threshold in the explain() trail
sromoam Oct 29, 2026
626f6dd
fix(348): resolve comparator keys on a nested model as the Python pat…
sromoam Oct 29, 2026
7dfab62
docs(348): document the nested-model comparator warning and the new d…
sromoam Oct 29, 2026
83f1556
docs(348): say the nested-object default threshold is fixed, not the …
sromoam Oct 30, 2026
6e51532
fix(348): plural warning verbs, keep ValueError for a list comparator…
sromoam Oct 30, 2026
fe8b830
Merge origin/dev into fix/334-348-importer-defaults
sromoam Nov 17, 2026
c6878eb
fix(importers): check an adopted comparator threshold and resolve nes…
sromoam Nov 17, 2026
2934248
docs(importers): state the threshold and clip defaults the importers …
sromoam Nov 17, 2026
dad0ca9
fix(importers): load a comparator that requires threshold on an array…
sromoam Nov 17, 2026
f7a4640
test(importers): pin the union, nested-warning and explain() behaviou…
sromoam Nov 17, 2026
1caa1cb
docs(importers): correct the free-form clip, nested comparator and wa…
sromoam Nov 17, 2026
ff19b01
docs(importers): scope the free-form clip claim to each object, and n…
sromoam Nov 17, 2026
a7ab802
docs(thresholds): state that an invalid field threshold raises, on ev…
sromoam Nov 17, 2026
09dcedd
fix(thresholds): raise on a field threshold that is not a number from…
sromoam Nov 17, 2026
a17802c
test(thresholds): pin the raise for an invalid field threshold on eve…
sromoam Nov 17, 2026
4f0fb4a
docs(thresholds): one message per path, int or float only, match_thre…
sromoam Nov 17, 2026
f5ad746
fix(thresholds): check Annotated fields, quote values as written, no …
sromoam Nov 17, 2026
3991537
test(thresholds): pin the per-path messages, Annotated, postponed ann…
sromoam Nov 17, 2026
be9b0b0
fix(thresholds): load an in-range Decimal, Fraction or numpy threshol…
sromoam Nov 17, 2026
d78cb3c
fix(thresholds): give every threshold message a fix, and the list ref…
sromoam Nov 17, 2026
526061b
fix(thresholds): check a forward-referenced field when the class is d…
sromoam Nov 17, 2026
7aa8375
docs(thresholds): a number from 0.0 to 1.0, on the class, config and …
sromoam Nov 17, 2026
55e4023
fix(thresholds): keep the runtime match_threshold check of evaluate()…
sromoam Nov 17, 2026
1654b58
fix(thresholds): check forward-referenced lists, keep numpy verdicts,…
sromoam Nov 17, 2026
32febb2
fix(importers): name a titled schema's model in its warnings, and say…
sromoam Nov 17, 2026
89b7e07
docs(thresholds): scope the runtime check, forward-referenced lists, …
sromoam Nov 17, 2026
9794614
docs(thresholds): a bare alias name for a list is ignored once resolv…
sromoam Nov 17, 2026
9d4a8a5
chore: merge origin/dev into fix/334-348-importer-defaults
sromoam Nov 17, 2026
0cad533
fix(thresholds): check an Annotated field whose type is defined furth…
sromoam Nov 17, 2026
4e59553
docs(thresholds): numpy float16 and float32 compare as Python floats,…
sromoam Nov 17, 2026
f7c7782
fix(auto): a runtime match_threshold=False does not warn that the thr…
sromoam Nov 17, 2026
60cc3a2
fix(thresholds): correct the threshold messages whose advice was wron…
sromoam Nov 17, 2026
d77fb56
docs(thresholds): scope the numpy, runtime, class match_threshold and…
sromoam Nov 17, 2026
e9228d7
fix(thresholds): evaluate Annotated metadata as pydantic does, once p…
sromoam Nov 17, 2026
44d21f9
fix(thresholds): a list-of-models message no longer tells an element …
sromoam Nov 17, 2026
96f5567
fix(thresholds): an unresolved dict or tuple gets the usual fix, and …
sromoam Nov 17, 2026
c4612ba
docs(thresholds): scope the Python list warning, name match_threshold…
sromoam Nov 17, 2026
9b2b5a9
docs(changelog): rewrap the threshold-rule paragraph
sromoam Nov 17, 2026
3a18858
test(thresholds): pin that a numpy float16 or float32 match_threshold…
sromoam Nov 17, 2026
cb26400
test(thresholds): drop the postponed Annotated case from the dict-or-…
sromoam Nov 17, 2026
8ce3b28
Revert "fix(thresholds): evaluate Annotated metadata as pydantic does…
sromoam Nov 17, 2026
5d85b9b
Revert "fix(thresholds): check an Annotated field whose type is defin…
sromoam Nov 17, 2026
605ea32
docs(thresholds): an Annotated field written as a string that names s…
sromoam Nov 17, 2026
a5230d5
fix(thresholds): a class loads when the working directory no longer e…
sromoam Nov 18, 2026
d86e94e
docs(importers): a threshold a custom comparator's constructor sets i…
sromoam Nov 18, 2026
43579b1
docs(thresholds): scope the Annotated, numpy float64 and array-sentin…
sromoam Nov 18, 2026
2b8d1b0
fix(evaluate): a runtime match_threshold of any real type in range is…
sromoam Nov 18, 2026
f7149a4
docs(thresholds): scope the Set at, None and unread-key claims
sromoam Nov 18, 2026
a93086a
docs(changelog): give the TP-to-FD example for a comparator's constru…
sromoam Nov 18, 2026
726726f
ci(thresholds): mark the test's exec calls reviewed, and skip the mad…
sromoam Nov 18, 2026
f0800a4
Merge origin/dev into fix/334-348-importer-defaults
sromoam Nov 23, 2026
b78859f
test(thresholds): patch in the NaN threshold the report test needs
sromoam Nov 23, 2026
e7ccbdc
test(thresholds): name the bool match_threshold test for the refusal …
sromoam Nov 23, 2026
619b714
fix(importers): name the model in the nested-model warnings as the er…
sromoam Nov 23, 2026
006f558
Merge dev into fix/334-348-importer-defaults
sromoam Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(thresholds): raise on a field threshold that is not a number from…
… 0.0 to 1.0

- The threshold a field ends up with is checked on all three paths, with
  one message from comparable_field._check_threshold. It names the model
  (for a schema, x-aws-stickler-model-name or the title, never
  "DynamicModel(fields: ...)"), the field path, the source as the author
  wrote it, the value with its type when not a number, the range, and the
  likely fix ("For 85%, use 0.85", "write 0.9 without quotes"). From a
  comparator it also names the field-level key that overrides it.
- Python: StructuredModel.__init_subclass__ now checks
  ComparableField(threshold=...) and an adopted comparator threshold such
  as LevenshteinComparator(threshold=85). Neither was checked, so at 85 an
  identical pair scored 0.0 FD.
- Config and schema: an adopted comparator_config /
  x-aws-stickler-comparator-config threshold raises instead of being
  ignored with a UserWarning (c6878eb), on a scalar and on a nested model.
  The field-level threshold / x-aws-stickler-threshold errors use the same
  message, and now refuse a bool, which loaded as 1.
- Not checked: a comparator threshold the field overrides (the evaluator
  never reads it; binary_compare() is the only other reader) and one on a
  list of models, which pairs on match_threshold and already warns. No
  comparator constructor checks its threshold, since a custom comparator
  may use it for something else.
- Valid is a real number (numbers.Real, so a numpy scalar still passes),
  not bool, from 0.0 to 1.0 inclusive; NaN and infinity fail.
- Removes the warn-and-ignore tests, and updates the three schema tests
  that matched the old x-aws-stickler-threshold message.
  • Loading branch information
sromoam committed Nov 17, 2026
commit 09dcedd2f7ad76fd01a00df523b96c3b02b4b3e0
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
with comparison configuration parameters.
"""

import math
import numbers
from typing import Any, Dict, Optional

from pydantic import Field
Expand Down Expand Up @@ -73,17 +75,88 @@ def _named_comparator_threshold(comparator: BaseComparator) -> Optional[float]:
return getattr(comparator, "threshold", None)


def _number_text(value: float) -> str:
"""``85`` for ``85`` or ``85.0``, else the repr, for an error message."""
return repr(int(value)) if float(value).is_integer() else repr(value)


def _threshold_problem(value: Any) -> Optional[str]:
"""Why ``value`` cannot gate a field, with the likely fix, or ``None``.

A threshold is a real number from 0.0 to 1.0. ``bool`` is refused although
it is an ``int``. ``numbers.Real`` rather than ``(int, float)`` so a numpy
scalar, which a Python model may pass, is still a number.
"""
if isinstance(value, bool):
return f"{value!r} is a boolean, not a number."
if isinstance(value, str):
try:
parsed = float(value)
except ValueError:
return f"{value!r} is a string, not a number."
if not math.isfinite(parsed):
return f"{value!r} is a string, not a number."
if _threshold_problem(parsed) is None:
return f"{value!r} is a string; write {value.strip()} without quotes."
hint = _threshold_problem(parsed)
return f"{value!r} is a string; write a number without quotes. {hint}"
if not isinstance(value, numbers.Real):
return f"{value!r} is a {type(value).__name__}, not a number."
if math.isnan(value):
return "NaN never compares, so no pair would match."
if value < 0:
return f"{value!r} is negative, so every pair would match."
if math.isinf(value):
return f"{value!r} is not finite, so no pair would match."
if value > 100:
return f"{value!r} is above 1.0, so no pair would match."
if value > 1:
return f"For {_number_text(value)}%, use {round(value / 100, 12)!r}."
return None


def _is_valid_threshold(value: Any) -> bool:
"""Whether ``value`` can gate a field: a real number from 0.0 to 1.0.
"""Whether ``value`` can gate a field: a real number from 0.0 to 1.0."""
return _threshold_problem(value) is None


The importers check a threshold named on a comparator with this before
adopting it, since only a field-level ``threshold`` is range-checked on
load. ``bool`` is refused although it is an ``int``; NaN fails the range.
def _check_threshold(
value: Any,
*,
field: str,
model: str,
source: str,
field_key: Optional[str] = None,
) -> None:
"""Raise ``ValueError`` if ``value`` cannot be the threshold of ``field``.

One message for all three paths. ``source`` is where the value came from,
as the author wrote it: ``ComparableField(threshold=85)``,
``comparator_config.threshold``, ``x-aws-stickler-threshold``.
``field_key`` is given when the value came from a comparator: it names the
field-level setting that would override it.

Only a value that becomes the field's threshold is checked here, never a
comparator's own: a custom comparator may use ``threshold`` for something
else, and the evaluator reads a comparator's threshold only when the field
adopts it.
"""
return (
isinstance(value, (int, float))
and not isinstance(value, bool)
and 0.0 <= value <= 1.0
problem = _threshold_problem(value)
if problem is None:
return
shown = repr(value)
if isinstance(value, bool) or not isinstance(value, numbers.Real):
shown += f" ({type(value).__name__})"
where = f"field {field!r}" + (f" of model {model!r}" if model else "")
override = (
f" Or set {field_key} to override the comparator's value."
if field_key
else ""
)
raise ValueError(
f"Invalid threshold for {where}: {source} gives {shown}, but a threshold "
"is a number from 0.0 to 1.0, the fraction of similarity a match needs. "
f"{problem}{override}"
)


Expand Down Expand Up @@ -144,6 +217,12 @@ def ComparableField(
ComparableField(comparator=ExactComparator())
# 0.5. A comparator's *default* threshold is not adopted;
# see _named_comparator_threshold for why.

The threshold the field ends up with, its own or the
comparator's, must be a number from 0.0 to 1.0. Anything
else (85, -1, "0.9", True, NaN) raises ``ValueError`` when
the ``StructuredModel`` class is defined, naming the model,
the field and the value.
weight: Weight of this field in overall score calculation (default: 1.0)
default: Default value for the field (default: unset, which means
None, or what ``default_factory`` returns if one is given).
Expand Down
169 changes: 76 additions & 93 deletions src/stickler/structured_object_evaluator/models/field_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
from stickler.utils.deprecation import warn_once

from .comparable_field import (
_LEGACY_DEFAULT_THRESHOLD,
ComparableField,
_check_threshold,
_is_valid_threshold,
_mark_unstated,
_named_comparator_threshold,
Expand Down Expand Up @@ -236,9 +236,8 @@ def _nested_model_comparator_threshold(
``comparator`` is the instance built from a named comparator, or ``None`` when
the field gives only a config. Returns the threshold to adopt or ``None``,
the names of the config keys that have no effect, and a named threshold that
is not a number from 0.0 to 1.0 (``None`` if there is none). That one is
reported by its value rather than raised on: these keys were accepted and
dropped before, so refusing one now would break a config that loads.
is not a number from 0.0 to 1.0 (``None`` if there is none). The caller
raises on that one unless the field states its own threshold, which wins.
"""
named = (
_named_comparator_threshold(comparator)
Expand All @@ -259,35 +258,41 @@ def _nested_model_comparator_threshold(
return adopted, ignored, rejected


def _rejected_threshold_warning(
field_path: str,
def _model_label(model_id: str) -> str:
"""The model's name for an error: ``model_identity`` without its field list.

``model_identity`` appends ``(fields: ...)`` to an unnamed model so two of
them dedupe apart. A reader knows the class as ``DynamicModel``. A
``model_name`` is an identifier, so it cannot contain the parenthesis.
"""
return model_id.partition("(")[0]


def _check_comparator_threshold(
value: Any,
comparator: Any,
config: Mapping,
*,
model_id: str,
source: str,
default: Any,
threshold_key: str,
) -> str:
"""The warning for a comparator threshold that is not a number from 0.0 to 1.0.
field: str,
model: str,
config_source: str,
field_key: str,
) -> None:
"""Raise if a comparator threshold the field adopts is not from 0.0 to 1.0.

A field-level threshold out of range raises on load. A comparator threshold
was never adopted before, so it loaded whatever its value; it is now read,
and adopting ``85`` or ``"0.9"`` failed every pair or raised on every
``compare_with``. It is ignored instead, which scores the field as before.
Adopted unchecked, 85 failed every pair, ``"0.9"`` raised on every
``compare_with`` and -1 passed every pair. ``config_source`` names the
config key, as the author wrote it; a threshold the comparator's own
constructor set is named by the comparator instead.
"""
return (
f"{source} {value!r} on field '{field_path}'{_of_model(model_id)} is not "
f"a number from 0.0 to 1.0, so it is ignored and the field keeps its "
f"default threshold of {default!r}. To gate the field, set "
f"{threshold_key} to a value from 0.0 to 1.0."
source = (
config_source
if "threshold" in config
else f"comparator {type(comparator).__name__!r} (its own threshold)"
)
_check_threshold(
value, field=field, model=model, source=source, field_key=field_key
)


def _comparator_threshold_source(comparator: Any, config: Mapping, config_key: str):
"""Where a comparator's named threshold was written, for a warning."""
if "threshold" in config:
return f"'{config_key}' threshold"
return f"The threshold set by comparator '{type(comparator).__name__}'"


def _config_keys_phrase(config_key: str, keys: List[str]) -> str:
Expand Down Expand Up @@ -533,39 +538,25 @@ def convert_field_config(
# comparator, then inference, so a comparator threshold outranks an
# inferred one: the author wrote it.
#
# A comparator threshold is adopted only if it could have been written
# as the field's `threshold`, which is range-checked on load. Otherwise
# it is ignored with a warning, and the field keeps the default it had
# before comparator thresholds were read, so nothing that loads raises.
# A comparator threshold the field adopts is checked as the field's own
# `threshold` is, and raises on load. A field `threshold` wins, so the
# comparator's is then not read and not checked.
threshold = field_config.get("threshold")

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.

Should-fix: explain() now contradicts its own row. Config {"type":"str","comparator":"auto","comparator_config":{"threshold":0.9}} resolves threshold 0.9, but why still says ['type:str -> LevenshteinComparator@0.7'], with no override note. A field-level threshold gets config: threshold=0.6 (overrides above) (L361-368), but nothing records the newly adopted comparator threshold here. On dev the trail matched, because the comparator threshold was ignored.

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.

Good catch. The trail now names an adopted comparator threshold the same way it names a field threshold: config: comparator_config.threshold=0.9 (overrides above). Fixed in 60703e0, with a test that fails without it. Across a 2,112-cell sweep, why now never contradicts its row on either path (dev had 168).

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 60703e0, and vawsgit confirmed it in the 2026-10-30 review. It still holds at a93086a: your config gives why: ['type:str -> LevenshteinComparator@0.7', 'config: comparator_config.threshold=0.9 (overrides above)'].

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.

High: comparator_config.threshold is adopted on primitive, list and dict fields without the 0.0-1.0 and numeric check that the field-level threshold gets.

Measured on head merged into dev (daeb226), compared with the merge base:

comparator_config.threshold head merged into dev merge base
85 'Acme Corp' vs 'Acme Corp' scores 0.0, FD, no warning 1.0, TP
"0.9" (string) loads, then every compare_with raises TypeError: '>=' not supported 1.0, TP
-1 'Acme Corp' vs 'Zzz Inc' (0.111) is TP FD

In all three cases, model_from_json(M.to_stickler_config()) then raises ValueError ("threshold must be between 0.0 and 1.0, got 85"), so the model cannot reload its own export. The merge base round-trips all three. Apply the field-threshold validation to the adopted value, at both this line and json_schema_importer.py:834.

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.

Good catch, thanks for the table. This is now the field-threshold validation, and it raises. An adopted comparator_config threshold is checked exactly as a field threshold is: anything that is not a number from 0.0 to 1.0 raises ValueError when the config loads, on a scalar field and on a nested model. So 85, "0.9" and -1 from your table fail at model_from_json() instead of scoring, and no such model exists to export. The message quotes the key as written, names the model and the field, and spells out the fix:

ValueError: Invalid threshold for field 'total' of model 'Invoice': the field sets no "threshold", so it adopts its comparator's: "comparator_config": {"threshold": 85}. A threshold is the minimum similarity score for a match, from 0.0 to 1.0. 85 is above 1.0, so even identical values would not match. If 85 is a percentage, write "comparator_config": {"threshold": 0.85}, or "threshold": 0.85 on the field, which wins over the comparator's.

A field threshold still wins, and then the comparator's value is neither read nor checked. On a list_structured_model field it is not read either, so it warns instead. The same rule covers match_threshold on the model and on a nested-model field, and true, which used to load as 1, is refused for both.

The Python path gets the same check when the class is defined. ComparableField(threshold=85) and an adopted LevenshteinComparator(threshold=85) were not checked at all, so an identical pair scored 0.0. They now raise, also on an Annotated field and on a field whose type is defined further down the module. Not yet checked at class definition: an Annotated field whose annotation is a string, as under from __future__ import annotations, that names something defined further down, its type or a value in its ComparableField(...). It loads as on dev, and checking it is tracked as a follow-up:

ValueError: Invalid threshold for field 'vendor' of model 'Invoice': ComparableField sets no threshold, so the field adopts its comparator's: LevenshteinComparator(threshold=85). A threshold is the minimum similarity score for a match, from 0.0 to 1.0. 85 is above 1.0, so even identical values would not match. If 85 is a percentage, write LevenshteinComparator(threshold=0.85), or ComparableField(threshold=0.85), which wins over the comparator's. (Set at invoice_models.py:6.)

A field whose type is defined further down is read as adopting its comparator's threshold, since stickler cannot tell yet whether it is a list of models. So List[Color] with an Enum Color below raises, as it does with Color above. So does List["Later"] with a model Later below, which dev never read, and that message says to remove the comparator. A Decimal, Fraction or numpy number from 0.0 to 1.0 loads, converted with float(). A numpy float16 or float32 threshold or match_threshold then compares as a Python float, so a score within its rounding below it moves from TP to FD: 0.89999997 against np.float32(0.9) was a TP on dev and is an FD now.

The runtime match_threshold of evaluate() and eval_for() keeps dev's check and message for a plain pydantic model, and a StructuredModel's value is not checked. The check now runs on every call and converts any real number in range with float(), so np.int64(1) or Decimal('0.5') scores as on dev. Giving it the shared rule and message is a follow-up. Fixed in 09dcedd, f5ad746, be9b0b0, d78cb3c, 526061b, 55e4023, 1654b58, f7c7782, 60cc3a2, 44d21f9, 96f5567, a5230d5 and 2b8d1b0, replacing the warning from c6878eb, with tests in a17802c, 3991537 and 3a18858 and in each fix commit, and docs in a7ab802, 4f0fb4a, 7aa8375, 89b7e07, 9794614, 4e59553, d77fb56, c4612ba, 605ea32, d86e94e, 43579b1, f7149a4 and a93086a.

@vawsgit vawsgit Nov 18, 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.

Correction to my comment above: asking to "apply the field-threshold validation to the adopted value" asked for a raise on the config path. Under the #443 decision that was wrong for 1.0.2. The fix that meets both this finding and #443: warn, and do not adopt an invalid comparator_config.threshold. Then 85 no longer scores an identical pair 0.0, and a warning does not stop model_from_json(M.to_stickler_config()) from reloading, as it does on dev. Raise in 1.1.0. Details in the review at 19:25.

named = _named_comparator_threshold(comparator)
adopted = threshold is None and _is_valid_threshold(named)
threshold_defaulted = (
threshold is None
and not adopted
and (inferred is not None or named is not None)
)
if threshold_defaulted:
threshold = (
inferred.threshold if inferred is not None else _LEGACY_DEFAULT_THRESHOLD
if threshold is None and named is not None:
_check_comparator_threshold(
named,
comparator,
comparator_config,
field=field_path,
model=_model_label(model_id),
config_source="comparator_config.threshold",
field_key="the field's threshold",
)
if named is not None:
warn_once(
"field-config-comparator-threshold-out-of-range",
f"{model_id}|{field_path}|{named!r}",
_rejected_threshold_warning(
field_path,
named,
model_id=model_id,
source=_comparator_threshold_source(
comparator, comparator_config, "comparator_config"
),
default=threshold,
threshold_key="'threshold'",
),
category=UserWarning,
stacklevel=_stacklevel_outside_stickler(through_warn_once=True),
)
adopted = threshold is None and named is not None
threshold_defaulted = threshold is None and not adopted and inferred is not None
if threshold_defaulted:
threshold = inferred.threshold
weight = field_config.get("weight", inferred.weight if inferred else 1.0)
clip_under_threshold = field_config.get("clip_under_threshold")
clip_inferred = clip_under_threshold is None and inferred is not None
Expand Down Expand Up @@ -791,6 +782,16 @@ def _convert_nested_model_field(
if ignored_keys:
ignored.append(_config_keys_phrase("comparator_config", ignored_keys))
stated = "threshold" in field_config
if rejected is not None and not stated:
_check_comparator_threshold(
rejected,
named_comparator,
raw_config if isinstance(raw_config, Mapping) else {},
field=field_path,
model=_model_label(model_id),
config_source="comparator_config.threshold",
field_key="the field's threshold",
)
if ignored:
warn_once(

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.

Medium: the new nested-model warnings do not include the model name, so Python's default warning deduplication hides them for a second model.

Loading Invoice and then Receipt, both with addr: {structured_model, comparator: ExactComparator}, prints one warning. Two schemas with x-aws-stickler-comparator on property address also print one. This contradicts dynamic-models.md:588-590 ("on every import", "once per model, path and key"). The schema copies (json_schema_importer.py:446 and :735) use the default stacklevel, and line 673 attributes the warning to library code when models nest two levels deep.

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 c6878eb, with docs in 2934248 and 1caa1cb. The nested-model warnings now name the model, so the default filter no longer folds Receipt into Invoice. On the schema path they use the title when there is no x-aws-stickler-model-name, as the errors do (32febb2). The stacklevel is found by walking out of the package, so they point at the caller at any depth on both paths: o.addr and p.o.addr on the config path, and the same plus a $ref on the schema path (f7a4640 pins the schema case). The docs no longer say "on every import": from_json_schema() does not deduplicate its warnings, and Python's filter decides how often they show. Two untitled schemas with no x-aws-stickler-model-name that share the same top-level property names are still one model to the filter, as two configs without model_name are. The unknown-key warnings in the same table still lack the model name and a nested stacklevel. That is unchanged from dev, so I've left it out of this PR, and 1caa1cb corrects the docs sentence that implied every row names the model.

"nested-model-comparator-keys",
Expand All @@ -814,25 +815,6 @@ def _convert_nested_model_field(
category=UserWarning,
stacklevel=_stacklevel_outside_stickler(through_warn_once=True),
)
if rejected is not None and not stated:
warn_once(
"nested-model-comparator-threshold-out-of-range",
f"{model_id}|{field_path}|{rejected!r}",
_rejected_threshold_warning(
field_path,
rejected,
model_id=model_id,
source=_comparator_threshold_source(
named_comparator,
raw_config if isinstance(raw_config, Mapping) else {},
"comparator_config",
),
default=0.7,
threshold_key="'threshold'",
),
category=UserWarning,
stacklevel=_stacklevel_outside_stickler(through_warn_once=True),
)

# Unused for scoring; ComparableField requires one. Carries an adopted
# comparator threshold, so `ComparableField` resolves it exactly as for
Expand Down Expand Up @@ -1019,22 +1001,23 @@ def validate_field_config(
raise ValueError(f"Invalid comparator for field '{field_name}': {e}")

# Validate numeric parameters
numeric_params = ["threshold", "weight"]
for param in numeric_params:
if param in field_config:
value = field_config[param]
if not isinstance(value, (int, float)):
raise ValueError(
f"Field '{field_name}' parameter '{param}' must be numeric, got {type(value)}"
)
if param == "threshold" and not (0.0 <= value <= 1.0):
raise ValueError(
f"Field '{field_name}' threshold must be between 0.0 and 1.0, got {value}"
)
if param == "weight" and value < 0:
raise ValueError(
f"Field '{field_name}' weight must be non-negative, got {value}"
)
if "threshold" in field_config:
_check_threshold(
field_config["threshold"],
field=path,
model=_model_label(model_id),
source="threshold",
)
if "weight" in field_config:
value = field_config["weight"]
if not isinstance(value, (int, float)):
raise ValueError(
f"Field '{field_name}' parameter 'weight' must be numeric, got {type(value)}"
)
if value < 0:
raise ValueError(
f"Field '{field_name}' weight must be non-negative, got {value}"
)

# Validate boolean parameters
boolean_params = ["required", "clip_under_threshold"]
Expand Down
Loading