Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
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
35 changes: 35 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,41 @@ Each release links to full notes on the
merging the two readers into one implementation
([#383](https://github.com/awslabs/stickler/issues/383))

- **Breaking:** a Stickler config and a JSON Schema now resolve an unstated
`threshold` and `clip_under_threshold` the way the Python path does. Both
importers filled in their own defaults (0.5 and `true`) before building the
field, so every imported field read as "the author stated this", and the two
defaults that key on that were skipped:
- **A threshold named on the comparator reaches the field.**
`"comparator_config": {"threshold": 0.9}` (or
`x-aws-stickler-comparator-config`) with no field `threshold` gated at the
importer's own default instead (0.5 for a string), so a pair scoring 0.78
was a TP there and an FD in Python. It is 0.9 on all
three paths now. A field threshold still wins, and a comparator threshold
outranks an inferred one
([#334](https://github.com/awslabs/stickler/issues/334)).
- **A mapping field keeps its partial credit.** A `dict` field naming a
comparator, or a list of them, defaulted to `clip_under_threshold: true`,
so ANLS\* partial credit below the threshold was zeroed: 0.0 where Python
reports 0.3333 for two of three keys wrong. It now defaults to `false` on
both importers, as it does in Python; an explicit `true` is still honoured
([#348](https://github.com/awslabs/stickler/issues/348)).

Any other field that states neither is unchanged. The schema path's
free-form object default (`ExactComparator` at 1.0, #348 item 1) is unchanged
too, except that its `clip_under_threshold` now reads `false`; Exact scores
0 or 1, so its scores do not move

- **Breaking:** `x-aws-stickler-comparator` or
`x-aws-stickler-comparator-config` on an object property with `properties`
now raises `ValueError`. An object is scored field by field, so neither was
ever read, and `explain()` reported the placeholder `LevenshteinComparator`
as the author's explicit choice. The config path already refuses `comparator`
on a `structured_model` field. No released `to_json_schema()` writes either
key there, so exported schemas still import. Move it onto the properties
inside the object
([#348](https://github.com/awslabs/stickler/issues/348))

- **Breaking:** `match_threshold` on a **primitive** field now raises
`ValueError`. It is the object-level threshold; nothing read it on a leaf, so
`"match_threshold": 0.99` beside a `float` left that field at `threshold` 0.5
Expand Down
8 changes: 6 additions & 2 deletions docs/docs/Advanced/dynamic-models.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,10 @@ The `x-aws-stickler-*` extensions control comparison behavior on each property:

| Extension | Purpose | Example |
|-----------|---------|---------|
| `x-aws-stickler-comparator` | Comparison algorithm | `"LevenshteinComparator"` |
| `x-aws-stickler-comparator` | Comparison algorithm. Raises on an object with `properties`, which is scored field by field; set it on the properties inside | `"LevenshteinComparator"` |
| `x-aws-stickler-threshold` | Match threshold (0.0--1.0). Read on a scalar, an object, and an array of scalars; **ignored on an array of models** -- an array whose `items` declare `properties` -- where the element class's `x-aws-stickler-match-threshold` is the gate. Read, not ignored, on an array of free-form `{"type": "object"}` items, which become `List[dict]` | `0.8` |
| `x-aws-stickler-weight` | Field importance weight | `2.0` |
| `x-aws-stickler-clip-under-threshold` | Zero out scores below threshold | `true` |
| `x-aws-stickler-clip-under-threshold` | Zero out scores below threshold. Defaults to `false` on a free-form object, which keeps its partial credit | `true` |
| `x-aws-stickler-model-name` | Class name (object-level) | `"Invoice"` |
| `x-aws-stickler-match-threshold` | Hungarian match threshold (object-level) | `0.75` |
| `x-aws-stickler-infer-unspecified` | Infer comparators for properties that name none (object-level). See [Inferring unspecified fields](#inferring-unspecified-fields) | `true` |
Expand Down Expand Up @@ -248,6 +248,10 @@ Person = StructuredModel.model_from_json(person_config)
}
```

A key the field leaves out resolves as it does on the Python path: a `threshold` in
`comparator_config` is adopted when `threshold` is absent, and a `dict` field
defaults to `clip_under_threshold: false`, so its partial credit survives.

**Nested model fields** use `"type": "structured_model"` with a nested `"fields"` object. **List of models** use `"type": "list_structured_model"`. **Optional models** use `"type": "optional_structured_model"`.

A key that is not listed above is not read. Rather than being dropped in silence, it emits a `UserWarning` naming the key, the full field path (`billing.city`), and the keys that position does accept; the model still builds, without the key. `match_threshold` is the exception: it is the object-level threshold, so on a primitive field it raises rather than warns — use `threshold` there.
Expand Down
11 changes: 7 additions & 4 deletions docs/docs/Guides/Evaluation/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,10 +186,10 @@ Add these extensions to any property in your JSON Schema to control comparison b

| Extension | Type | Default | Purpose |
|-----------|------|---------|---------|
| `x-aws-stickler-comparator` | string | Type-dependent | Comparison algorithm (e.g., `"ExactComparator"`, `"LevenshteinComparator"`) |
| `x-aws-stickler-comparator` | string | Type-dependent | Comparison algorithm (e.g., `"ExactComparator"`, `"LevenshteinComparator"`). Raises on an object with `properties`, which is scored field by field |
| `x-aws-stickler-threshold` | number (0.0--1.0) | see below | Match classification cutoff. Read on a scalar, an object, and an array of scalars. **Ignored on an array of models** -- an array whose `items` declare `properties` -- where pairing is gated by the element class's `x-aws-stickler-match-threshold`, and a declared value warns there. Read, not ignored, on an array of free-form `{"type": "object"}` items |
| `x-aws-stickler-weight` | number (> 0.0) | 1.0 | Field importance multiplier |
| `x-aws-stickler-clip-under-threshold` | boolean | `true` | Zero out scores below threshold |
| `x-aws-stickler-clip-under-threshold` | boolean | `true`, `false` on a free-form object | Zero out scores below threshold |
| `x-aws-stickler-model-name` | string | `"DynamicModel"` | Name of the generated Python class (root level) |
| `x-aws-stickler-match-threshold` | number (0.0--1.0) | 0.7 | Model-level matching threshold for Hungarian algorithm (root level) |
| `x-aws-stickler-infer-unspecified` | boolean | `false` | Infer a comparator, threshold and weight for any property that names none, using the same rules `stickler.evaluate()` uses (root level) |
Expand All @@ -209,8 +209,11 @@ on the position, because different positions fall back to different defaults:

A scalar is plain when it has none of the keywords in the last row. Any other
`format` (`email`, `hostname`, ...) leaves it plain. Declaring the key explicitly
overrides the default in every position that reads it.
`x-aws-stickler-clip-under-threshold` defaults to `true` in all of them.
overrides the default in every position that reads it. Without it, a `threshold`
in `x-aws-stickler-comparator-config` overrides the default instead, as it does
on the Python path. `x-aws-stickler-clip-under-threshold` defaults to `true`,
except on a free-form object or an array of them, which keeps its partial credit
and defaults to `false`.

### Example Schema

Expand Down
6 changes: 4 additions & 2 deletions src/stickler/structured_object_evaluator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,9 +230,11 @@ result = gt.compare_with(pred)

- `x-aws-stickler-comparator`: comparator **class name**, such as `"ExactComparator"`, `"FuzzyComparator"`, `"LevenshteinComparator"`, `"SemanticComparator"`. Lowercase aliases are not accepted and raise.
- `x-aws-stickler-comparator-config`: keyword arguments for that comparator's constructor
- `x-aws-stickler-threshold`: matching threshold, 0.0 to 1.0 (default: 0.5)
- `x-aws-stickler-threshold`: matching threshold, 0.0 to 1.0 (default: a `threshold` in `x-aws-stickler-comparator-config`, else the type default)
- `x-aws-stickler-weight`: field importance weight (default: 1.0)
- `x-aws-stickler-clip-under-threshold`: clip scores below threshold to 0.0 (boolean, default: true)
- `x-aws-stickler-clip-under-threshold`: clip scores below threshold to 0.0 (boolean, default: true; false on a free-form object)

`x-aws-stickler-comparator` and `-comparator-config` raise on an object with `properties`: it is scored field by field, so it has no comparator.

**Object-level extensions**, valid on the root schema or on any object-typed property:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,28 @@ def _named_comparator_threshold(comparator: BaseComparator) -> Optional[float]:
return getattr(comparator, "threshold", None)


def _mark_unstated(field, *, threshold: bool = False, clip: bool = False) -> None:
"""Record that an importer, not the author, supplied ``threshold`` / ``clip``.

The importers have defaults ``ComparableField`` cannot express: a JSON Schema
type default such as ``ExactComparator@1.0`` for an enum, a nested object's
0.7, an inferred value. They pass the number, then clear the marker here, so
the markers keep meaning "the author wrote this on the field". Passing the
number alone marked every imported field as explicitly configured (#334).

Written onto the closure ``ComparableField`` just returned, which no caller
holds a reference to yet, so the shared-field hazard in
``StructuredModel._install_object_grade_comparators`` does not apply.
"""
extra = field.json_schema_extra
if not callable(extra):
return
if threshold:
extra._threshold_explicit = False
if clip:
extra._clip_explicit = False


def ComparableField(
comparator: Optional[BaseComparator] = None,
threshold: Optional[float] = None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@

from stickler.utils.deprecation import warn_once

from .comparable_field import ComparableField
from .comparable_field import (
ComparableField,
_mark_unstated,
_named_comparator_threshold,
)
from .comparator_registry import create_comparator, normalize_comparator_config
from .type_resolver import resolve_type_string

Expand Down Expand Up @@ -326,15 +330,26 @@ def convert_field_config(
except (KeyError, TypeError) as e:
raise ValueError(f"Invalid comparator for field '{field_name}': {e}")

# Extract other field parameters
threshold = field_config.get(
"threshold", inferred.threshold if inferred else 0.5
# `None` for what the config does not state, so `ComparableField` resolves
# it exactly as it does on the Python path. Defaulting to 0.5 and True here
# marked both as stated, which discarded a threshold named in
# `comparator_config` (#334) and suppressed the object-grade clip default,
# zeroing a dict field's partial credit (#348). Precedence is field, then
# comparator, then inference, so a comparator threshold outranks an
# inferred one: the author wrote it.
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.

threshold_inferred = (
threshold is None
and inferred is not None
and _named_comparator_threshold(comparator) is None
)
if threshold_inferred:
threshold = inferred.threshold
weight = field_config.get("weight", inferred.weight if inferred else 1.0)
clip_under_threshold = field_config.get(
"clip_under_threshold",
inferred.clip_under_threshold if inferred else True,
)
clip_under_threshold = field_config.get("clip_under_threshold")
clip_inferred = clip_under_threshold is None and inferred is not None
if clip_inferred:
clip_under_threshold = inferred.clip_under_threshold

# Name the parameters the author took back, so the trail cannot contradict
# the row it sits under. Inference fills only what the config left unnamed,
Expand Down Expand Up @@ -388,6 +403,9 @@ def convert_field_config(
description=description,
examples=examples,
)
_mark_unstated(
comparable_field, threshold=threshold_inferred, clip=clip_inferred
)

# Record what was inferred, so `explain()` reports the reason and a
# `source` naming what drove the choice (`type`, `name-token`) rather than
Expand Down Expand Up @@ -494,7 +512,8 @@ def _convert_nested_model_field(
# CRITICAL FIX: Create ComparableField for nested models to enable proper comparison
# Extract threshold and weight from field configuration
weight = field_config.get("weight", 1.0) # Default weight
clip_under_threshold = field_config.get("clip_under_threshold", True)
# `None` when unstated, for the reason given in `convert_field_config`.
clip_under_threshold = field_config.get("clip_under_threshold")

# For list_structured_model, don't set threshold (Hungarian matching uses model's match_threshold)
# For single structured_model, use threshold from config
Expand Down Expand Up @@ -528,6 +547,8 @@ def _convert_nested_model_field(
description=description,
examples=examples,
)
# The 0.7 above is this path's default, not the author's.
_mark_unstated(comparable_field, threshold="threshold" not in field_config)

return field_type, comparable_field

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@
from pydantic import AnyUrl, BaseModel, TypeAdapter
from pydantic.fields import FieldInfo

from .comparable_field import ComparableField
from .comparable_field import (
ComparableField,
_mark_unstated,
_named_comparator_threshold,
)
from .comparator_registry import create_comparator, normalize_comparator_config
from .field_converter import AUTO_COMPARATOR
from .model_factory import ModelFactory
Expand Down Expand Up @@ -412,6 +416,24 @@ def _convert_field(
"recursive field-by-field comparison",
"this object",
)
# Refused rather than dropped. An object with `properties` is scored
# field by field, so no comparator is ever read here, and accepting
# one let `explain()` report the placeholder below as the author's
# explicit choice (#348). The config path refuses `comparator` on a
# `structured_model` field the same way.
extra = field_info.json_schema_extra
for key in (
"x-aws-stickler-comparator",
"x-aws-stickler-comparator-config",

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 (a follow-up is fine): misplaced comparator keys are refused unevenly. This raises on x-aws-stickler-comparator-config on an object with properties, but the config path silently accepts comparator_config on structured_model, list_structured_model and optional_structured_model (no warning, threshold left at 0.7/0.5). The schema path also accepts it on an array of objects, with only a warning, and explain() reports LevenshteinComparator, 0.9, source: explicit. The comment above says the config path refuses comparator the same way, which is true for comparator but not comparator_config. Also, Python does adopt a comparator threshold on a nested model (ComparableField(comparator=ExactComparator(threshold=0.8)) gives 0.8 and gates), so for a config carrying a threshold, the error could point to x-aws-stickler-threshold rather than "move it onto the properties".

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.

Agreed, and thanks for the Python measurement. I measured the Python path on a single nested model, an optional one and a list, and both importers now match it (626f6dd): a comparator threshold on a single or optional nested model is read and gates, and a named comparator, or any other config key, warns with one wording on both paths, pointing at threshold / x-aws-stickler-threshold. On a list, comparator config warns and points at match_threshold / x-aws-stickler-match-threshold, and explain() no longer reports it. The new raise is gone, so nothing that loaded before fails. A comparator name on a list of models is unchanged, since Python itself raises there for anything but Levenshtein; that and the nested-object 0.7 default are filed as #468.

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.

The explain() part vawsgit flagged as still open is fixed in c6878eb. A named comparator on a nested model is now installed, as on the Python path, so explain() reports ExactComparator on all three paths instead of the placeholder Levenshtein. It is still never called, and it still warns. Your array-of-objects point was fixed in 626f6dd, and explain() reports 0.5 there now. The list_structured_model asymmetry (the config path raises on any comparator, the schema path accepts Levenshtein) is left for #468, as you suggested.

One correction to my earlier reply: "nothing that loaded before fails" no longer holds. A threshold or match_threshold that is not a number from 0.0 to 1.0 now raises on load, as vawsgit asked in the thread on field_converter.py:427. These loaded on dev and now raise:

  • Config and schema: "threshold": true and x-aws-stickler-threshold: true (loaded as 1), "match_threshold": true and x-aws-stickler-match-threshold: true, and a comparator-config threshold such as 85 or "0.9" (loaded, never read).
  • Python: any such value in ComparableField(threshold=...), in a comparator threshold the field adopts, or in the match_threshold class attribute, and ModelFactory.create_model_from_fields(match_threshold=True). A field threshold of 85 scored an identical pair 0.0. A class match_threshold of 85 made every list pair of that class an FD.
  • Python: an out-of-range comparator threshold on a list whose element type is defined further down, such as List["Later"] with LevenshteinComparator(threshold=85). Dev never read it there. stickler cannot tell yet whether Later is a model, and the message says to remove the comparator if it is.

The runtime match_threshold of evaluate() and eval_for() keeps dev's check and message for a plain pydantic model, now on every call, and now converts any real number in range with float(), and is not checked for a StructuredModel.

):
if isinstance(extra, dict) and key in extra:
raise ValueError(
f"{key} is not read on field '{field_path}': it is an "
"object with properties, scored by recursive "
"field-by-field comparison, so it has no comparator. "
"Remove it, and set it on the properties inside the "
"object instead."
)
comparison_field = self._make_comparison_field(
field_info,
comparator_name="LevenshteinComparator",
Expand All @@ -431,8 +453,10 @@ def _convert_field(
# configurable. See #317.
threshold=extensions.get("threshold", 0.7),
weight=extensions.get("weight", 1.0),
clip_under_threshold=extensions.get("clip_under_threshold", True),
clip_under_threshold=extensions.get("clip_under_threshold"),
)
# The 0.7 is this path's default, not the author's (#334).
_mark_unstated(comparison_field, threshold="threshold" not in extensions)
return final_type, comparison_field

if origin in (list, List, set):
Expand Down Expand Up @@ -738,18 +762,33 @@ def _comparison_from_extensions(
# the same silent drop one branch over.
comparator = create_comparator(comparator_name, author_config)

# Precedence is field, then comparator, then this path's default, as on
# the Python path. The default (inferred, or the type's row) used to be
# passed whenever the field stated nothing, which discarded a threshold
# named in `x-aws-stickler-comparator-config` (#334). `None` lets
# `ComparableField` adopt it. An unstated clip is likewise left `None`, so
# an object-grade field gets its unclipped default (#348).
declared_threshold = extensions.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.

Same trail gap on the schema path: with x-aws-stickler-infer-unspecified and a float, explain() reports 0.9 while why says @0.95.

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. The schema path recorded no overrides at all, so x-aws-stickler-threshold, -weight and -clip-under-threshold beside inference also showed the inferred numbers. It now appends schema: x-aws-stickler-comparator-config.threshold=0.9 (overrides above), and the same for those keys.

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. It still holds at a93086a: why: ['type:float -> NumericComparator(rel_tol=0.001)@0.95', 'schema: x-aws-stickler-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.

Same gap as field_converter.py:427: x-aws-stickler-comparator-config.threshold is adopted without the 0.0-1.0 and numeric check.

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.

Same fix on the schema path (09dcedd, message reworded in f5ad746, 1654b58 and 60cc3a2). An adopted x-aws-stickler-comparator-config threshold is checked as x-aws-stickler-threshold is, and raises on import. That includes an object with properties, where only that threshold is read. The value is quoted as JSON, and the model is named by x-aws-stickler-model-name, then title:

ValueError: Invalid threshold for field 'total' of model 'Invoice': the field sets no "x-aws-stickler-threshold", so it adopts its comparator's: "x-aws-stickler-comparator-config": {"threshold": "0.9"}. A threshold is the minimum similarity score for a match, from 0.0 to 1.0. "0.9" is a string, not a number. Write "x-aws-stickler-comparator-config": {"threshold": 0.9}, or "x-aws-stickler-threshold": 0.9 on the property, which wins over the comparator's.

On an array of objects the comparator config is not read, so it warns instead. Pairing there uses x-aws-stickler-match-threshold in items, which is checked.

threshold_defaulted = (
declared_threshold is None
and _named_comparator_threshold(comparator) is None
)
clip = extensions.get("clip_under_threshold")
clip_inferred = clip is None and inferred is not None
field = self._make_comparison_field(
field_info,
comparator=comparator,
threshold=extensions.get(
"threshold", inferred.threshold if inferred else threshold
threshold=(
(inferred.threshold if inferred else threshold)
if threshold_defaulted
else declared_threshold
),
weight=extensions.get("weight", inferred.weight if inferred else 1.0),
clip_under_threshold=extensions.get(
"clip_under_threshold",
inferred.clip_under_threshold if inferred else True,
clip_under_threshold=(
inferred.clip_under_threshold if clip_inferred else clip
),
)
_mark_unstated(field, threshold=threshold_defaulted, clip=clip_inferred)
if inferred is not None and inferred.provenance:
extra_callable = field.json_schema_extra
if callable(extra_callable):
Expand All @@ -764,7 +803,7 @@ def _make_comparison_field(
comparator_name: Optional[str] = None,
threshold: Optional[float],
weight: float,
clip_under_threshold: bool,
clip_under_threshold: Optional[bool],
) -> FieldInfo:
if comparator is None:
comparator = create_comparator(comparator_name, {})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -717,13 +717,25 @@ def __init_subclass__(cls, **kwargs):
# "sets threshold=0.0" points at a `ComparableField` argument
# absent from the call site -- the same misattribution this
# PR fixes for the `List[StructuredModel]` error one screen up.
field_wrote_it = getattr(
field_default.json_schema_extra, "_threshold_explicit", True
#
# "Not stated on the field" does not imply "from the
# comparator": an importer clears the marker on its own
# defaults too, and an inferred mapping threshold copies a
# `match_threshold` of 0.0. So the comparator is credited only
# when it actually named a threshold.
extra = field_default.json_schema_extra
from_comparator = not getattr(
extra, "_threshold_explicit", True
) and (
_named_comparator_threshold(
getattr(extra, "_comparator_instance", None)
)
is not None
)
_warn_if_threshold_is_zero(
temp_schema["x-comparison"].get("threshold"),
f"{_model_identity(cls.__name__, cls.__annotations__)}.{field_name}",
"threshold" if field_wrote_it else "comparator threshold",
"comparator threshold" if from_comparator else "threshold",
)

# `match_threshold` is a plain class attribute rather than a field, so
Expand Down
Loading
Loading