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): check forward-referenced lists, keep numpy verdicts,…
… spell out every fix

Behaviour:
- A forward-referenced list (List[Color] with Color defined below) is
  checked as adopting its comparator's threshold, like any unresolved
  annotation: stickler cannot tell yet whether the element is a model,
  and nothing checks the field once it resolves. An Enum, str subclass,
  plain BaseModel or union element loaded with an 85 and scored wrong;
  it now raises at class definition, as when defined above. On a list of
  models defined below, an invalid comparator threshold raises where the
  resolved form only warns; the message says to remove the comparator.
- A PEP 695 alias is read as the type it names, so a list-of-models alias
  with an unused comparator threshold loads, as on dev.
- A Decimal, Fraction or numpy number is converted with float(), not via
  str: np.float32(0.9) compares at 0.8999999761581421, as before, so
  verdicts do not move. A 0-d numpy array loads as its number again, and
  a numpy boolean is read as a boolean.

Messages:
- Every fix is spelled out in full ("write ComparableField(threshold=0.85)",
  'write "threshold": 0.85'), and "no pair would match" says what it
  means ("even identical values would not match").
- The Python adoption line reads "ComparableField sets no threshold, so
  the field adopts its comparator's: ...", and the field's threshold
  "wins over the comparator's".
- A threshold on a list of models "has no effect": remove it, and to
  change how items match, add match_threshold to the element class. A
  valid one is headed "Unused threshold", and is quoted as written.
- A nested model says its comparator is never called and the field takes
  only its threshold; the importers say to delete the key that holds it.
- true points at 1.0 and at clip_under_threshold, false at the default,
  NaN at the empty cell it usually comes from.
- A custom comparator that may set its own threshold is named with where
  it is defined, and how to pass threshold through.
- Locations are relative to the working directory, or "line 4 of the
  notebook cell", and a class match_threshold names the class line.
- The List[StructuredModel] comparator-threshold warning names the model
  and element class, says what to do, and points at the caller.
  • Loading branch information
sromoam committed Nov 17, 2026
commit 1654b587bb63bf651373815d249ae0f949ebfbbe
Original file line number Diff line number Diff line change
Expand Up @@ -213,9 +213,14 @@ class MyModel(StructuredModel):
if from_comparator is not None
else _LEGACY_DEFAULT_THRESHOLD
)
# A valid Decimal, Fraction or numpy number becomes the float it means, so
# the metadata, `explain()` and both exports carry a float. An invalid one
# is kept as written, for the error the class raises when it is defined.
# A valid Decimal, Fraction or numpy number becomes the float `float()`
# gives, so the field's metadata, `explain()` and the field threshold both
# exports write are a float. The comparator keeps the value it was given:
# one that exports its own threshold (ANLSStarComparator's config) still
# writes it as given. An invalid one is kept as written, for the error the
# class raises when it is defined. So is the value as written, for the
# error a List[StructuredModel] field raises for a valid one.
threshold_as_written = threshold
threshold = normalize_threshold(threshold)

# Create serializable metadata for JSON schema compatibility
Expand Down Expand Up @@ -246,6 +251,7 @@ def json_schema_extra_func(schema: Dict[str, Any]) -> None:
# the class is defined and so would otherwise point only at its `class` line.
set_at = caller_location()
json_schema_extra_func._set_at = set_at
json_schema_extra_func._threshold_as_written = threshold_as_written

# Merge with existing json_schema_extra if provided
existing_json_schema_extra = field_kwargs.get("json_schema_extra", {})
Expand All @@ -265,6 +271,7 @@ def enhanced_json_schema_extra(schema: Dict[str, Any]) -> None:
enhanced_json_schema_extra._clip_under_threshold = clip_under_threshold
enhanced_json_schema_extra._comparison_metadata = serializable_metadata
enhanced_json_schema_extra._set_at = set_at
enhanced_json_schema_extra._threshold_as_written = threshold_as_written
final_json_schema_extra = enhanced_json_schema_extra
elif isinstance(existing_json_schema_extra, dict):

Expand All @@ -282,6 +289,7 @@ def enhanced_json_schema_extra(schema: Dict[str, Any]) -> None:
enhanced_json_schema_extra._clip_under_threshold = clip_under_threshold
enhanced_json_schema_extra._comparison_metadata = serializable_metadata
enhanced_json_schema_extra._set_at = set_at
enhanced_json_schema_extra._threshold_as_written = threshold_as_written
final_json_schema_extra = enhanced_json_schema_extra
else:
final_json_schema_extra = json_schema_extra_func
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
is_threshold_error,
is_valid_threshold,
match_threshold_error,
outside_location,
)

#: Every key a top-level model config may carry, as read by ``create_model``.
Expand Down Expand Up @@ -369,6 +370,7 @@ def _validate_name_and_threshold(
spelling=CONFIG if config else PYTHON,
model=model,
field=field,
set_at=None if config else outside_location(),
)

@staticmethod
Expand Down
100 changes: 78 additions & 22 deletions src/stickler/structured_object_evaluator/models/structured_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,12 @@
SCHEMA,
as_threshold,
is_valid_threshold,
list_comparator_warning,
list_threshold_error,
match_threshold_error,
outside_location,
python_comparator_source,
stacklevel_outside,
threshold_error,
)

Expand Down Expand Up @@ -250,6 +253,26 @@ def _is_unresolved(annotation: Any) -> bool:
return any(_is_unresolved(arg) for arg in args)


def _unalias(annotation: Any) -> Any:
"""``list[Item]`` for a PEP 695 alias ``type Items = list[Item]``, also in a union.

pydantic keeps the alias as the field's annotation, so a list test on it
answers False although the field is scored as the list it names. An alias
whose value names a class not defined yet is left as it is.
"""
for _ in range(10):
if type(annotation).__name__ != "TypeAliasType":
break
try:
annotation = annotation.__value__
except NameError:
return annotation
arms = get_args(annotation) if union_args(annotation) else ()
if arms and any(type(arm).__name__ == "TypeAliasType" for arm in arms):
return Union[tuple(_unalias(arm) for arm in arms)]
return annotation


def _list_element_name(annotation: Any) -> str:
"""``Item`` for ``List[Item]``, ``Optional[List[Item]]`` or ``list[Item] | None``.

Expand All @@ -273,7 +296,9 @@ def _list_element_name(annotation: Any) -> str:
element = element.__forward_arg__
if isinstance(element, str):
return _bare_name(element) or "the element class"
return getattr(element, "__name__", "the element class")
if not isinstance(element, type):
return "the element class" # a union of classes, say
return element.__name__
return "the element class"


Expand Down Expand Up @@ -790,7 +815,11 @@ def __init_subclass__(cls, **kwargs):
# object a true positive, the misconfiguration
# warn_if_threshold_is_zero exists to flag.
raise list_threshold_error(
threshold,
getattr(
field_default.json_schema_extra,
"_threshold_as_written",
threshold,
),
spelling=PYTHON,
field=field_name,
model=cls.__name__,
Expand Down Expand Up @@ -840,16 +869,28 @@ def __init_subclass__(cls, **kwargs):
# warns. The sibling `_warn_if_threshold_is_zero`
# call below uses this helper for exactly that
# reason, and I keyed on the name anyway.
comparator = getattr(
field_default.json_schema_extra,
"_comparator_instance",
None,
)
warn_once(
"list-of-models-comparator-threshold",
f"{_model_identity(cls.__name__, cls.__annotations__)}"
f".{field_name}",
f"Field '{field_name}' is a List[StructuredModel], so the "
f"threshold set on its comparator is not consulted: "
f"Hungarian matching pairs items using the element class's "
f"'match_threshold'. Set 'match_threshold' on the element "
f"class if you meant to change how items are paired.",
list_comparator_warning(
_named_comparator_threshold(comparator),
comparator=python_comparator_source(
comparator
),
field=field_name,
model=cls.__name__,
element=_list_element_name(field_type),
),
category=UserWarning,
stacklevel=stacklevel_outside(
through_warn_once=True
),
)

# Comparator validation - only flag if explicitly set to non-default type
Expand Down Expand Up @@ -910,7 +951,12 @@ def __init_subclass__(cls, **kwargs):
or isinstance(value, (property, classmethod, staticmethod))
or is_valid_threshold(value)
):
raise match_threshold_error(value, spelling=PYTHON, model=cls.__name__)
raise match_threshold_error(

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.

This raise turns code that loads on dev into ValueError in a 1.0.2 patch release. #443 decided such changes become warnings (it names #408). Warn here and keep the dev behaviour; raise in 1.1.0.

Reproduction: match_threshold = True on a class loads on dev (and scores as 1.0), raises Invalid match threshold for model 'M': match_threshold = True is a boolean, not a number here.

value,
spelling=PYTHON,
model=cls.__name__,
set_at=outside_location(),
)
number = as_threshold(value)
if number is not None and number is not value:
# A Decimal, Fraction or numpy number, as the float it means.
Expand Down Expand Up @@ -944,11 +990,12 @@ def _check_field_thresholds(cls) -> None:
An annotation still unresolved (a forward reference, such as ``addr:
Address`` under ``from __future__ import annotations`` with ``Address``
defined below) is checked now, as one that adopts its comparator's
threshold, unless it is visibly a list (``List["Item"]``,
``"Optional[List[Item]]"``). Nothing checks it once it resolves, and
only a list of models does not adopt. A bare name that resolves to a
list alias is the one shape this reads wrong, and only for an invalid
threshold.
threshold, even when it is visibly a list (``List["Item"]``): stickler
cannot tell yet whether ``Item`` is a model, and nothing checks the
field once it resolves. Only a list of models does not adopt, so an
invalid comparator threshold there raises, though it would only warn
once resolved; the message says to remove the comparator in that case.
A PEP 695 alias is read as the type it names.
"""
for field_name, field_info in cls.model_fields.items():
if field_name == _EXTRA_FIELDS_KEY:
Expand All @@ -961,10 +1008,10 @@ def _check_field_thresholds(cls) -> None:
if is_valid_threshold(threshold):
continue
annotation = field_info.annotation
if not getattr(extra, "_threshold_explicit", True) and (
_is_visibly_list(annotation)
if _is_unresolved(annotation)
else cls._is_list_of_structured_model_type(annotation)
if (
not getattr(extra, "_threshold_explicit", True)
and not _is_unresolved(annotation)
and cls._is_list_of_structured_model_type(_unalias(annotation))
):
continue
raise cls._threshold_error(field_name, extra, threshold, annotation)

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.

This raise turns code that loads on dev into ValueError in a 1.0.2 patch release. #443 decided such changes become warnings (it names #408). Warn here and keep the dev behaviour; raise in 1.1.0.

Reproduction: class M(StructuredModel): x: str = ComparableField(threshold=85) loads on dev, raises Invalid threshold for field 'x' of model 'M' here. Same for threshold=True, 1.5, -1 and an adopted LevenshteinComparator(threshold=85).

Expand All @@ -980,22 +1027,31 @@ def _threshold_error(
getattr(extra, "_comparator_instance", None)
)
unresolved = _is_unresolved(annotation)
resolved = _unalias(annotation)
list_element = None
if (
_is_visibly_list(annotation)
if unresolved
else cls._is_list_of_structured_model_type(annotation)
else cls._is_list_of_structured_model_type(resolved)
):
list_element = _list_element_name(annotation)
list_element = _list_element_name(resolved)
nested = (
comparator is not None
and not unresolved
and cls._is_structured_model_type(resolved)
)
nested_model = None
if nested:
inner = unwrap_optional(unwrap_annotated(resolved))[0]
nested_model = getattr(inner, "__name__", None)
return threshold_error(
threshold,
spelling=PYTHON,
field=field_name,
model=cls.__name__,
comparator=comparator,
nested=comparator is not None
and not unresolved
and cls._is_structured_model_type(annotation),
nested=nested,
nested_model=nested_model,
list_element=list_element,
list_unresolved=unresolved,
set_at=getattr(extra, "_set_at", None),
Expand Down
Loading