Repository navigation
Conversation
…h does Both importers filled in their own defaults (threshold 0.5, clip True) before constructing the ComparableField, so every imported field read as explicitly configured and the defaults keyed on those markers never ran: - A threshold named on the comparator (comparator_config / x-aws-stickler-comparator-config) was discarded, so a field gated at 0.9 was TP from an importer and FD in Python. Precedence is now field, then comparator, then the path's own default (inference or the schema type row) on all three paths. - The object-grade clip default was suppressed, zeroing a dict field's partial credit below threshold (0.0 vs Python's 0.3333). An unstated clip is now passed as None. - Where an importer must pass its own default (schema type rows, nested object 0.7, inferred values), the explicitness marker is cleared after construction so it keeps meaning "the author wrote this". x-aws-stickler-comparator / -comparator-config on an object property with properties now raises instead of being dropped while explain() reported the placeholder as explicit, matching the config path's refusal of comparator on a structured_model field. Closes #334. Refs #348.
…t named one Review of the previous commit. Clearing `_threshold_explicit` on importer defaults made the zero-threshold warning read "sets comparator threshold=0.0" for an inferred mapping threshold copied from `match_threshold: 0.0`. It now credits the comparator only when the comparator named the threshold. Also: tests for the list-of-mappings clip default, the schema free-form object default, and the object-property refusal across type-list, anyOf, $ref and allOf spellings; CHANGELOG no longer says the importer gate was always 0.5.
Security Scan ResultsASH Security Scan Report
Scan Metadata
SummaryScanner ResultsThe table below shows findings by scanner, with status based on severity thresholds and dependencies:
Report generated by Automated Security Helper (ASH) at 2026-11-23T17:47:27+00:00 |
harrycav
left a comment
There was a problem hiding this comment.
Reviewed on dev 4a6ef00 + 530e77f. Parity sweep, 660 combinations across 15 field types, comparator/threshold/clip stated and unstated, class match_threshold set and unset, config and schema paths each compared against Python: 606 cells differ on dev, 334 here; 272 fixed, 0 new. The rest is pre-existing #348. explain(), to_json_schema() and to_stickler_config() match the engine in every changed case, and both round trips keep comparator, threshold and clip. The #334 clip pin holds. Full suite (3997) and the Strands contract (821) pass, and the snapshot doesn't move. Every Breaking change I measured is disclosed.
Two should-fix, inline below. Plus:
- Nit: the
from_json_schemadocstring (structured_model.py:983-986) still says threshold default 0.5 and clip default true, and doesn't mention the new raise. The new error is also missing from the troubleshooting table indynamic-models.md. - Nit: the PR body's "18 remaining mismatches" undercounts. Schema
enumanddatewith a named comparator and no threshold also resolve 1.0 against Python's 0.5. That comes from the documented type defaults, not a regression. - Release: this is
!with two Breaking entries, in a milestone described as non-breaking only, so it should follow the #443 decision.
| # 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") |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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).
| # 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") |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| extra = field_info.json_schema_extra | ||
| for key in ( | ||
| "x-aws-stickler-comparator", | ||
| "x-aws-stickler-comparator-config", |
There was a problem hiding this comment.
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".
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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": trueandx-aws-stickler-threshold: true(loaded as 1),"match_threshold": trueandx-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 thematch_thresholdclass attribute, andModelFactory.create_model_from_fields(match_threshold=True). A field threshold of 85 scored an identical pair 0.0. A classmatch_thresholdof 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"]withLevenshteinComparator(threshold=85). Dev never read it there. stickler cannot tell yet whetherLateris 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.
A threshold taken from comparator_config / x-aws-stickler-comparator-config replaces the inferred one, but the trail still quoted only the inferred @0.7 / @0.95, so explain() contradicted its own row. Record it the way the config path already records a field threshold. The schema path recorded no overrides at all, so x-aws-stickler-threshold, -weight and -clip-under-threshold are named there too.
…h does ComparableField(comparator=X(threshold=t)) on a nested StructuredModel resolves t and gates the child; the comparator itself is never called. On List[StructuredModel] Python warns that a comparator threshold is not consulted, since Hungarian matching pairs on the element match_threshold. The importers disagreed with that and with each other: - config: comparator_config on structured_model / optional_structured_model was dropped in silence (threshold left at 0.7), and comparator raised. - schema: x-aws-stickler-comparator / -comparator-config on an object with properties raised (new on this branch; dropped in silence on dev). - list_structured_model dropped comparator_config in silence, while an array of objects forwarded it, so explain() reported it as the explicit threshold. Now, on both importers, a threshold in the comparator config is read on a single or optional nested model (field threshold still wins), and every key that is not read warns, in one wording, naming where the effective setting goes. Nothing that loaded before raises. "auto" on a nested model and a named comparator on list_structured_model still raise, as before.
…efaults from_json_schema's docstring still gave threshold 0.5 and clip true as the defaults. The extension tables said a comparator on an object raises; it now warns, and a threshold in its config is read. The troubleshooting table gains the warning. CHANGELOG: the first entry says plainly that these are fixes to the documented Python behaviour, and the comparator-on-object entry moves to Fixed, no longer Breaking.
…class's match_threshold
…, and correct the README and test names
|
@harrycav, thanks for the review. The three inline threads have replies. On the rest:
Full suite 4243 passed; Strands contract 821 passed with the snapshot unchanged. |
vawsgit
left a comment
There was a problem hiding this comment.
needs changes
Measured on head 6e51532 against the merge base e94dc21. The high finding was also re-run on head merged into dev 52e8ef4 (daeb226), and it still reproduces there. Of harrycav's three comments, two are resolved. The explain() part of 4418023816 remains (inline at field_converter.py:679).
Inline:
- High
field_converter.py:427andjson_schema_importer.py:834:comparator_config.thresholdis adopted without a 0.0-1.0 or numeric check. - Medium
field_converter.py:650: the two importers disagree about a nested model's named comparator. - Medium
field_converter.py:196: an invalid nested threshold produces a warning that gives the wrong reason. - Medium
json_schema_importer.py:752: rebuilding with{}gives an error that names no field. - Medium
field_converter.py:657: the warnings are deduplicated across models. - Medium
field_converter.py:679:explain()still reports the placeholder comparator. - Medium
structured_model.py:994: the docstrings state the old defaults.
Outside the diff: README.md (the PyPI long description) still gives the old defaults. Line 469 says clip defaults to true, line 471 says clipping is on, and line 347 lists fixed threshold defaults with no mention of an adopted comparator-config threshold. Two of the docs this PR updates link to that section. For example, an object field with ANLSStarComparator scores 0.3333 below threshold on head, where the README predicts 0.0. The json_schema_importer.py:559 finding is also outside the diff: a union-of-objects property (anyOf [A, B]) skips the new nested-model handling with no warning, which contradicts CHANGELOG.md:235.
| # 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") |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 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") |
There was a problem hiding this comment.
Same gap as field_converter.py:427: x-aws-stickler-comparator-config.threshold is adopted without the 0.0-1.0 and numeric check.
There was a problem hiding this comment.
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.
| comparator_threshold = None | ||
| if raw_config is not None and not isinstance(raw_config, Mapping): | ||
| ignored.append("'comparator_config'") | ||
| elif raw_config is not None: |
There was a problem hiding this comment.
Medium: the two importers disagree about a nested model's named comparator.
The config path asks a named comparator for its own threshold only when comparator_config is present. The schema path (json_schema_importer.py:432-436) always asks. Both paths warn that the comparator "has no effect", even when its threshold gates the field.
Example: a custom comparator whose __init__ sets threshold=0.95, on a nested model whose child scores 0.75. The schema path and the Python path gate at 0.95 (FD). The config path without comparator_config gates at 0.7 (TP). Removing the key, as the warning advises, changes FD to TP.
There was a problem hiding this comment.
Fixed in c6878eb. The config path now asks a named comparator for its threshold whether or not there is a comparator_config. Your case (the constructor sets 0.95, the child scores 0.75) gates at 0.95 and is an FD on the Python, config and schema paths. The warning no longer says only "has no effect". It reads "'comparator' has no effect on field 'addr' of model 'Inv' and is ignored, except for its threshold 0.95, which this field uses", and tells you to set threshold (x-aws-stickler-threshold on the schema path) to 0.95 to keep that threshold without the comparator. Following that advice keeps the FD. TestANestedModelAsksANamedComparatorForItsThreshold covers it.
| if comparator is not None | ||
| else comparator_config.get("threshold") | ||
| ) | ||
| adopted = ( |
There was a problem hiding this comment.
Medium: an out-of-range or non-numeric comparator_config.threshold on a nested model produces a warning that gives the wrong reason and points at a key that raises.
comparator_config: {threshold: 1.5} on a structured_model warns "has no effect ... scored field by field" and keeps 0.7. The warning does not name the value, while a valid 0.8 under the same key is read. It points the user at threshold / x-aws-stickler-threshold, and moving 1.5 there raises "threshold must be between 0.0 and 1.0". The schema path behaves the same way for an object with properties. Report the value and the range.
There was a problem hiding this comment.
Fixed: comparator_config: {threshold: 1.5} on a nested model now raises on load instead of being ignored, on both importers. The message gives the value and the range instead of "has no effect", and the fix it gives no longer leads to a raise or a warning:
ValueError: Invalid threshold for field 'addr' of model 'N': the field sets no "threshold", so it adopts its comparator's: "comparator_config": {"threshold": 1.5}. A threshold is the minimum similarity score for a match, from 0.0 to 1.0. 1.5 is above 1.0, so even identical values would not match. On a nested model, which is scored field by field, only the threshold in "comparator_config" is read. Delete "comparator_config", and write "threshold": 1.0 on the field to require a perfect similarity score.
The schema path says the same for x-aws-stickler-comparator-config on an object with properties. With a named comparator beside the config, it says the comparator is never called and to delete both keys, so the corrected config does not warn either. Fixed in 09dcedd, f5ad746, d78cb3c, 1654b58 and 60cc3a2.
| ) | ||
| if "comparator" in extensions: | ||
| try: | ||
| extensions["comparator"] = create_comparator( |
There was a problem hiding this comment.
Medium: rebuilding the comparator with create_comparator(name, {}) gives errors that name no field, and lets non-TypeError exceptions escape.
On an array of objects with both a comparator and a comparator-config, a comparator with a required argument fails like this: Failed to create NeedsPattern with config {}: missing 1 required positional argument. The message names no field, and it blames an argument the author did supply. A constructor that raises RuntimeError escapes from_json_schema, which documents only ValueError. A custom class named LevenshteinComparator that requires config loaded on the merge base and raises on head.
There was a problem hiding this comment.
Fixed in c6878eb and dad0ca9. On an array of objects, the comparator is now rebuilt with every config key except threshold, so a comparator that requires another key still builds. Your custom LevenshteinComparator case loads, as it does on dev. A comparator whose constructor requires threshold itself falls back to the one built from your full config (dad0ca9). It is never called there, so it loads as on dev, and explain() reports 0.5, as for any array of objects. If the comparator still cannot be built, the error is a ValueError naming the field and the key, whatever the constructor raised, so your RuntimeError case no longer escapes from_json_schema. Your NeedsPattern repro gets the same error as on dev: a List[StructuredModel] field cannot have a comparator.
| if ignored_keys: | ||
| ignored.append(_config_keys_phrase("comparator_config", ignored_keys)) | ||
| if ignored: | ||
| warn_once( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| # Unused for scoring; ComparableField requires one. Carries an adopted | ||
| # comparator threshold, so `ComparableField` resolves it exactly as for | ||
| # `ComparableField(comparator=X(threshold=t))`: field threshold first. | ||
| placeholder = ( |
There was a problem hiding this comment.
Medium: explain() still reports the placeholder comparator for a nested model with a named comparator. This is the unresolved part of harrycav's comment 4418023816.
On both importers, explain() reports {comparator: LevenshteinComparator, threshold: 0.7, source: explicit}, while the Python path reports ExactComparator. The PR body lists #348 item 7 as fixed. The merge base refused this config, so on the config path the wrong report is new. test_explain_does_not_report_it_as_chosen only asserts comparator != "ExactComparator", so it passes with the placeholder.
There was a problem hiding this comment.
You're right, the placeholder was the wrong answer too. Fixed in c6878eb. The named comparator is installed as on the Python path, so explain() and _get_comparison_info report ExactComparator on all three paths. It is still never called, and it still warns. The test now asserts that the three paths agree, rather than "not Exact". f7a4640 adds the same check for a named comparator with no config. When nothing is stated, the threshold in that row still reads 0.7 on the importers and 0.5 on Python. That is the nested-object default filed as #468.
|
|
||
| An object with properties is scored field by field, so a comparator on | ||
| it, and any comparator-config key but threshold, has no effect and emits | ||
| a UserWarning. On an array of objects no comparator config is read. |
There was a problem hiding this comment.
Medium: these docstrings state defaults the code no longer uses.
- The
from_json_schemadocstring says an array of objects reads no comparator config, and that clip is false only on a free-form object. In fact, an array of free-form objects with ANLSStar and threshold 0.3 gates at 0.3 with clip false. So[{a:1,b:2,c:3}]vs[{a:1,b:9,c:9}]is a TP at 0.3333 instead of the predicted 0.0. - The
model_from_jsondocstring (line 922, andmodel_factory.py:88) still says an unstated threshold defaults to 0.5. Levenshtein withcomparator_config.threshold: 0.9gates at 0.9.
There was a problem hiding this comment.
Fixed in 2934248, with wording in ff19b01, 7aa8375 and d86e94e. The from_json_schema docstring now says clip is false on a free-form object or an array of them, and that only an array of objects with properties reads no comparator config. The model_from_json and ModelFactory comments give the default as "a threshold named on the comparator (comparator_config or a custom constructor), else 0.5", and from_json_schema names both for x-aws-stickler-threshold. All three say that the threshold the field uses must be a number from 0.0 to 1.0, or loading raises ValueError.
…tuple fix test Partial revert of 96f5567. Its `Annotated[Dict[str, Later], ComparableField(threshold=85)]` case, under `from __future__ import annotations`, relied on evaluating the metadata of an Annotated annotation pydantic holds as a string (0cad533), which is being reverted. The rest of 96f5567 is kept.
…, once per declaring class" This reverts commit e9228d7. It builds on 0cad533, which evaluates the metadata of an Annotated annotation pydantic holds as a string, and is reverted next. Its namespace comes from the first frame outside stickler and pydantic, so a base class that overrides __pydantic_init_subclass__ moves it into the base's module: a false raise, and a wrong "Set at". Dict and Tuple stay in the test module's globals, since 96f5567's tests use them.
…ed further down" This reverts commit 0cad533. Evaluating the metadata of an Annotated annotation pydantic holds as a string did not evaluate it as pydantic does: a ComparableField that a later Field(json_schema_extra={...}) displaces, and pydantic drops, was still checked and raised. Such a field loads unchecked at class definition again, as on dev. Kept from the commits since: _unresolved_type_name and _element_match_threshold (60cc3a2), the unresolved dict-or-tuple fix (96f5567) and the PEP 695 docstring (4e59553). The docs are scoped next.
…omething defined later is not yet checked With 0cad533 and e9228d7 reverted, an Annotated annotation pydantic holds as one string (quoted whole, or under `from __future__ import annotations`) because its type or a value in its ComparableField(...) is defined further down loads unchecked at class definition, as on dev. - CHANGELOG Python bullet, Comparators guide and thresholds-and-metrics: say so where they say an Annotated field and a field whose type is defined further down are checked. This replaces the "`Annotated` fields included" of d77fb56. - thresholds-and-metrics: the list-of-models comparator warning needs an annotation that is already a list when the class is defined, written out or through an assigned alias. - Module README and the _check_field_thresholds docstring: drop the description of the reverted metadata evaluation (4e59553, c4612ba) and say such a field is not yet checked.
…xists location() made the file name relative with os.path.relpath, which calls os.getcwd() and raised FileNotFoundError when the working directory had been removed, so any ComparableField(...) failed to load. It now falls back to the full path, as for a file on another drive.
…s adopted too On a config or schema scalar, a registered comparator whose constructor passes a threshold to super().__init__() now gates the field, over 0.5 or a schema type default such as 1.0 for an enum, as ComparableField(comparator=...) already did. The CHANGELOG, README, Evaluation guide, module README and the model_from_json, ModelFactory and from_json_schema docstrings named only a comparator-config threshold. No built-in comparator sets one when built bare, so fields naming one do not move. A parity test pins the four shapes.
…el claims - Evaluation guide and the ComparableField docstring: an Annotated field written as a string that names something defined further down is not yet checked at class definition, as 605ea32 already says elsewhere. - CHANGELOG: the importers already loaded a numpy float64, a float subclass; only the other non-float numbers were refused. - Evaluation guide: on an array of models, x-aws-stickler-threshold 0.5 does not warn, since every earlier export wrote it.
… accepted as a float
On a plain pydantic model, evaluate(), eval_for() and from_pydantic()
checked match_threshold with isinstance(int, float) on every call, so
match_threshold=1 then np.int64(1), or 0.5 then Decimal('0.5') or
np.float32(0.5), raised where dev scored 1.0 from the cache. The check now
converts an in-range value with as_threshold, as class and field
thresholds are, and returns a float: an int, float, numpy integer or
floating, Decimal, Fraction or 0-d array is accepted on any call. A
Python bool still counts as 1.0 or 0.0. A string, a numpy boolean, NaN,
infinity or an out-of-range value raises the same message.
The cache is keyed on the converted float, so equal values share one
shadow model, and EvalSpec keeps that float for matched and explain().
- CHANGELOG and Thresholds and Metrics: a base class that overrides __init_subclass__ makes a class match_threshold's "Set at", and the list comparator warning, point at the line of that override. Field thresholds are unaffected. - structured_model.py comment and Thresholds and Metrics: None reads as unset only as a field threshold. A class match_threshold = None is let through, as before, and raises TypeError where it is read. - CHANGELOG: an unread comparator key warns when it is written on a field or property; on a $defs definition it is still ignored silently.
…ctor threshold A registered comparator whose constructor passes threshold=0.95 gated an imported string field at 0.5, so a pair it scores 0.9 was a TP; it is an FD at 0.95 now, as in Python.
…e-up order_models.py in coverage
vawsgit
left a comment
There was a problem hiding this comment.
needs changes
One blocker. The new threshold-validation layer raises ValueError for classes, configs and schemas that load on dev. This PR is in milestone 1.0.2, and the #443 decision says: "Changes that would turn a configuration that loads today into an error are converted to warnings instead (for example #408)." CHANGELOG.md line 15 on this branch also says patch releases ship no breaking changes.
The importer fix this PR is named for (#334, #348) is correct. It is reproduced, mutation-tested and parity-checked (details below).
What to change
- Turn every new raise for an invalid field threshold or
match_thresholdinto a warning in 1.0.2, and keep thedevbehaviour (for an importer'scomparator_config.threshold: do not adopt an invalid value). Raise in 1.1.0, the same waydevalready handled the three changes it moved there. Inline comments mark each raise site. - Restore
test_threshold_zero_warning.py::test_bool_is_not_reported_as_a_zero_thresholdto assert thatmatch_threshold = True/Falseloads (it now assertspytest.raises). - Correct the PR body. "Nothing that loads today raises" and "none that loads on dev raises on this branch" are false at this head.
- Optional, recommended: split the validation layer (
threshold_rule.py, the string-annotation parser instructured_model.py, the runtimematch_thresholdchanges andtest_threshold_validation.py, 536 tests) into its own PR. The title, body and Tests section of this PR do not describe it.
Reproduction (head 726726f against dev c70ca6e, PYTHONPATH set to each tree's src, stickler.__file__ checked)
== dev
ComparableField(threshold=85): loads
class match_threshold=True: loads
config threshold: true: loads
== 726726f
ComparableField(threshold=85): ValueError: Invalid threshold for field 'x' of model 'M': ComparableField(threshold=85) is out of range. ...
class match_threshold=True: ValueError: Invalid match threshold for model 'M': match_threshold = True is a boolean, not a number. ...
config threshold: true: ValueError: Invalid threshold for field 'x' of model 'Box': "threshold": true is a boolean, not a number. ...
The same holds for threshold=True, 1.5, -1, LevenshteinComparator(threshold=85) adopted by a field, schema x-aws-stickler-threshold: true, x-aws-stickler-match-threshold: true, config and schema comparator_config {"threshold": 85}, and runtime evaluate(..., match_threshold=np.True_). All load on dev and on 6e51532.
Some of these were working setups, not only broken ones:
truemeant 1.0 and scored as an exact match ondev.- A custom comparator that uses
thresholdas a distance worked through the importers, which never read it.WithinPixelswithcomparator_config {"threshold": 5}, 100 vs 103, scores1.0ondev. At this head it raisesInvalid threshold for field 'x' of model 'Box' ....
My previous review (6e51532): every finding is fixed
comparator_config.thresholdadopted unchecked: fixed, by raising. The fix itself is part of the blocker above: it must warn in 1.0.2.- Importers disagreed on a named comparator's constructor threshold on a nested model: fixed. Config, schema and Python all give
thr=0.95 FD=1(6e51532: config TP at 0.7). comparator_config {threshold: 1.5}gave the wrong reason: fixed. The message names the value and the range (also a raise, see above).create_comparator(name, {})errors named no field andRuntimeErrorescaped: fixed.NeedsPatternandNeedsThrmatchdevagain.- Warning deduplication hid warnings across models: fixed. Two models now give 2 warnings (6e51532: 1), and the warning points at the caller's line.
explain()reported the placeholder comparator: fixed. It reportsExactComparator, and the test asserts it exactly.- Stale docstrings: fixed.
- Root
README.mddefaults: fixed. - Union of objects: documented as not covered. Measured as the CHANGELOG says (no warning, threshold 0.8,
ExactComparator).
Verified and cleared
- CI is green at 726726f. At a93086a, coverage and bandit failed on the
exec(compile(..., "order_models.py"))test helpers. Commit 726726f fixed both (# nosec B102, coverage omit). - Full suite: 5167 passed, 11 skipped, 1 xfailed. The skips are the
bertextra (torch), 2 placeholder tests and the Strands e2e test, none in this diff. The PR merged into currentdevalso passes 5167. - All 8 rows of the PR body's table reproduced, config and schema,
devagainst head (for exampleACME-1000vsACNE-1009= 0.7778: TP at 0.5 ondev, FD at 0.9 at head; dict ANLS* 0.0 with clip, 0.3333 without). - Round trips through
to_stickler_config()andto_json_schema()keep comparator, threshold and clip for str, nested, dict and list-of-models fields. - No unintended score moves for single, list and optional nested models. Build time unchanged (0.138 s vs 0.143 s for 300 fields x10).
- Reverts 8ce3b28 and 5d85b9b leave no dead functions, and the docs match the reverted behaviour.
- Mutation testing: 16 of 16 mutants killed, including the config and schema defaults, the bool refusal, the range, the
explain()entry, the model name in warnings and the zero-threshold credit. - No CI matrix,
pyproject.tomlfloor oruv.lockregression againstdev.
Non-blocking (LOW)
- PR body counts are stale: it says 4243 passed and 45 parity tests; measured 5167 and 62. #407 at d581b21 now conflicts with this PR in
json_schema_importer.pyandCHANGELOG.md, so "a combined merge with #407 passes" no longer holds. - An untitled schema's warning names
'DynamicModel(fields: address)'._model_labelis applied only in errors. - A string
Annotatedfield naming a later type loads unchecked, and aftermodel_rebuild()its threshold of 85 is live. Documented, and the same ondev.
Not run: the bert extra tests (they do not touch this diff), and the body's 2,112-cell parity sweep and 488-config harvest (the script is not in the repo).
| and cls._is_list_of_structured_model_type(_unalias(annotation)) | ||
| ): | ||
| continue | ||
| raise cls._threshold_error(field_name, extra, threshold, annotation) |
There was a problem hiding this comment.
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).
| or isinstance(value, (property, classmethod, staticmethod)) | ||
| or is_valid_threshold(value) | ||
| ): | ||
| raise match_threshold_error( |
There was a problem hiding this comment.
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.
| if "threshold" in field_config and not is_valid_threshold( | ||
| field_config["threshold"] | ||
| ): | ||
| raise threshold_error( |
There was a problem hiding this comment.
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: config "threshold": true and comparator_config {"threshold": 85} both load on dev. A custom distance comparator (WithinPixels, comparator_config {"threshold": 5}, 100 vs 103) scores 1.0 on dev and raises here. For an invalid comparator_config.threshold, warn and do not adopt it.
| if not is_valid_threshold(match_threshold): | ||
| if model is None and field is None and model_name != "DynamicModel": | ||
| model = model_name | ||
| raise match_threshold_error( |
There was a problem hiding this comment.
| config path dropped it there and the schema path did too | ||
| ([#334](https://github.com/awslabs/stickler/issues/334)). An adopted | ||
| comparator threshold is checked as a field threshold is; see the next item. | ||
| - **A threshold that is not a number from 0.0 to 1.0 raises `ValueError` |
There was a problem hiding this comment.
This bullet announces new ValueErrors in the release that line 15 says ships no breaking changes. Once the raises become warnings, reword it as a warning that becomes an error in 1.1.0.
|
@vawsgit, thanks for the thorough pass. The seven inline items are fixed. The importer items are in c6878eb and dad0ca9. The threshold check is in 09dcedd, f5ad746, be9b0b0, d78cb3c, 526061b, 55e4023, 1654b58, f7c7782, a5230d5 and 2b8d1b0, and the message wording in 32febb2, 60cc3a2, 44d21f9 and 96f5567. Tests are in f7a4640, a17802c, 3991537 and 3a18858 and in each fix commit, and docs in 2934248, 1caa1cb, ff19b01, a7ab802, 4f0fb4a, 7aa8375, 89b7e07, 9794614, 4e59553, d77fb56, c4612ba, 605ea32, d86e94e, 43579b1, f7149a4 and a93086a. An out-of-range comparator threshold now raises The README now gives the adopted comparator-config threshold and the free-form clip default, and says the default ExactComparator scores 0.0 or 1.0, so there is no partial credit to keep. On the union of objects: when every arm declares properties, it resolves as the Python path does for a Union field. A comparator-config threshold gates it, and a named comparator is installed and never called, with no nested-model warning. A value that lands on a free-form arm is compared by that comparator, as on dev. I left the behaviour alone and scoped the CHANGELOG claim to arms that declare properties (1caa1cb, 7aa8375). The branch is merged up with dev (9d4a8a5). |
|
@harrycav, this follows the #443 decision, with one exception I chose for 1.0.2. The title dropped its The exception: a threshold or In the merge with dev (fe8b830), both CHANGELOG entries moved from the released 1.0.1 section into |
|
thanks for the work here. the #334 fix does what it says: a two things to look at before 1.0.2. on would you be open to keeping the 1.0.2 PR to the change that passes |
vawsgit
left a comment
There was a problem hiding this comment.
needs changes
The blocker from my review at 17:05 is not resolved. No commit has been pushed since 726726f. The replies at 17:07 answer the threads from the 2026-10-30 review. None of them answers the five inline comments on the raise sites. The top-level reply to harrycav keeps the threshold raise as "one exception I chose for 1.0.2".
The #443 decision does not allow that exception. It says: "Changes that would turn a configuration that loads today into an error are converted to warnings instead (for example #408)." An exception to a recorded release decision needs the maintainers' agreement on #443, not a choice inside this PR. digalaviz asked for the same split at 17:39.
The reason given for the exception is false for three inputs
The reply says "each such value scored wrongly or was never read before". I measured that on current dev (ad3d868) and on 726726f, with PYTHONPATH set to each tree's src and stickler.__file__ printed:
dev ad3d868 726726f
config "threshold": true, Levenshtein loads; same 1.0, near 0.0 ValueError: ... is a boolean, not a number
config "match_threshold": true loads; same 1.0 ValueError: ... is a boolean, not a number
custom WithinPixels, comparator_config {threshold: 5}, 100 vs 103
loads; score 1.0 ValueError: Invalid threshold for field 'x' of model 'Box' ...
ComparableField(threshold=85) loads; identical pair 0.0 ValueError: ... is out of range
class match_threshold = True loads ValueError: ... is a boolean, not a number
The first three rows are working setups. true loads as 1.0 and means an exact match. The custom comparator uses threshold as a distance, and dev never reads it as a similarity threshold. These users get a ValueError from a patch release with nothing wrong in their results. The fourth row is broken on dev, which is why it should warn. It still must not raise in 1.0.2.
A correction to my 2026-10-30 review
My comment on field_converter.py:427 asked to "apply the field-threshold validation to the adopted value". On the config path that validation raises, so I asked for a raise. That was wrong under #443, which had been posted three hours earlier. The author's "as vawsgit asked" is accurate for that one case. The fix that meets both the 2026-10-30 finding and #443: warn, and do not adopt the invalid comparator_config.threshold. The other raises (the Python path, true, match_threshold) were not asked for in any review.
What to change (unchanged from 17:05)
- Turn every new raise for an invalid field threshold or
match_thresholdinto aUserWarningin 1.0.2, and keep thedevbehaviour. For an importer'scomparator_config.threshold, do not adopt an invalid value. Raise in 1.1.0. The raise sites:stickler/src/stickler/structured_object_evaluator/models/structured_model.py
Lines 1078 to 1080 in 726726f
stickler/src/stickler/structured_object_evaluator/models/structured_model.py
Lines 1003 to 1005 in 726726f
stickler/src/stickler/structured_object_evaluator/models/field_converter.py
Lines 1040 to 1042 in 726726f
stickler/src/stickler/structured_object_evaluator/models/model_factory.py
Lines 367 to 369 in 726726f
- Restore
test_threshold_zero_warning.py::test_bool_is_not_reported_as_a_zero_thresholdto assert thatmatch_threshold = True/Falseloads. - Reword the
CHANGELOG.mdbullet at line 49 as a warning that becomes an error in 1.1.0. Line 14 says patch releases ship no breaking changes:Lines 13 to 15 in 726726f
- Correct the PR body. "Nothing that loads today raises" is false at this head.
- Optional, recommended (digalaviz asked the same): move the validation layer (
threshold_rule.py, the annotation parser instructured_model.py, the runtimematch_thresholdchanges andtest_threshold_validation.py) to a 1.1.0 PR, and keep this PR to the #334/#348 importer fix.
The importer fix for #334 and #348 is still correct. Everything listed as fixed and cleared in the 17:05 review stands, because the head has not changed.
If the maintainers agree on #443 that 1.0.2 may raise here, record that on #443 and I will re-review on that basis.
|
OK with the threshold exception, thanks: those values never scored correctly, so failing loudly is the better outcome. |
|
Hi @sromoam, a gentle reminder: the review from @vawsgit on Thanks again for the work here. |
Brings in v1.0.2 and the dev work since. Conflicts resolved: - json_schema_importer.py: the nested-model `_make_comparison_field` call keeps dev's `field_path=field_path` and this branch's `comparator=placeholder`. - CHANGELOG.md: dev's file as is, with this branch's two entries under [Unreleased] (Changed, Fixed) above the shipped [1.0.2] section. - docs/docs/Guides/Evaluation/README.md: the schema extension table keeps this branch's comparator, threshold-range and comparator-config text, and dev's List[StructuredModel] note, inference clip note and infer-unspecified wording. - tests/structured_object_evaluator/README.md: both paragraphs.
dev's report test built `ComparableField(threshold=nan)`, which this branch refuses at class definition. The report still drops a non-finite threshold, since a string `Annotated` annotation naming a later type loads one, so the test now patches the extracted thresholds instead of relying on that gap.
…rors do An untitled schema's warning said `of model 'DynamicModel(fields: address)'`, the warn-once identity, where its threshold error says `of an unnamed model (set title or x-aws-stickler-model-name to name it)`. The warning now takes the label and spelling the errors use, on the config path too, so a config without `model_name` reads `of an unnamed model (set model_name to name it)`. A named or titled model is named as before.
|
@vawsgit, thanks for both passes, and for the correction on
Current |
vawsgit
left a comment
There was a problem hiding this comment.
✅ LGTM!
The blocker in my reviews of 726726f is resolved. This PR is now on milestone 1.1.0. Those reviews asked to "raise in 1.1.0", and digalaviz asked on 11-18 for the validation to move to 1.1.0. The raises are now documented as a 1.1.0 breaking change. The importer fix for #334 and #348 is still correct.
My 2026-11-18 asks, at 619b714
- Warn in 1.0.2, raise in 1.1.0: resolved by the move to 1.1.0.
- Restore the bool test to assert that it loads: that ask applied only to 1.0.2. In 1.1.0 a bool is refused, so the test now asserts the raise (renamed in e7ccbdc).
- CHANGELOG: resolved. Both entries are under
[Unreleased], above## [1.0.2]. They say "raisesValueErrorin 1.1.0 … This is a breaking change" and list all five kinds of input. - PR body: resolved. It has a "Breaking in 1.1.0" section, and "nothing that loads today raises" is gone.
- Split the validation layer: declined with a reason (without the check, the #334 fix makes a
comparator_configthreshold of 85 score every pair 0.0 in silence). That ask was optional.
Verified at 619b714 (stickler.__file__ = this tree's src, Python 3.12, uv sync --extra llm --extra bert --frozen)
- Full suite: 6193 passed, 3 skipped, 1 xfailed. The skips are 2 placeholder tests and the Strands end-to-end test. With
strands-agents-evals==1.6.0installed,tests/integrationsgives 821 passed, 1 xfailed.ruff check .is clean anduv lock --checkpasses. - Every row of "Breaking in 1.1.0" reproduces: it loads on
devbf7c879 and raisesValueErrorat head. That covers config and schemathreshold: true, class, config and schemamatch_thresholdset to true,ComparableField(threshold=85 / 1.5 / -1), classmatch_threshold = 85, an adoptedLevenshteinComparator(threshold=85),comparator_config {"threshold": 85}, andWithinPixelswithcomparator_config {"threshold": 5}. ForWithinPixels, the documented fix (field"threshold": 0.5) loads and scores 1.0 at 103 and 0.0 at 110. - Before/after rows re-measured. Comparator threshold 0.9,
ACME-1000vsACNE-1009:dev0.7778, head 0.0, on config and schema. With fieldthreshold: 0.6added: 0.7778 on both trees. ANLS* dict with two of three keys wrong:dev0.0, head 0.3333. - 619b714: an untitled schema now warns
of an unnamed model (set title or x-aws-stickler-model-name to name it), the same wording as the error. A config withoutmodel_namesays(set model_name to name it). Named roots are still named. - Mutation tests. Reverting 619b714's
srcchange fails 2 tests, and forcing "unnamed" for every model fails 8. Removing the non-finite filter inhtml_reporter.pyfails the test b78859f patched, which still asserts{"total": 0.5}asdev's test did. - Merge f0800a4: the
_make_comparison_fieldcall atjson_schema_importer.py:851passes both #407'sfield_pathand this branch'scomparator=placeholder, and the signature accepts both. #407's tests pass. No line that #407 removed comes back. Nothing changes in.github/oruv.lock, and the onlypyproject.tomlchange is a coverageomitentry. - CI is green at 619b714 (15 of 15 checks).
Before merge (not a code finding)
GitHub reports the PR as conflicting with dev bf7c879. A trial merge conflicts in CHANGELOG.md only, because both sides add entries under [Unreleased]. Keeping both fixes it. On that trial merge the full suite gives 6773 passed, 2 skipped, 2 xfailed.
Non-blocking (LOW)
RELEASING.md:25says a minor release has "no breaking changes". The threeValueErrors thatdevalready schedules for 1.1.0 each shipped a warning in 1.0.x first. These raises did not, because 1.0.2 shipped without one, so 1.1.0 goes straight from a silent load to aValueError.strands-agents-evalspinsstickler-eval>=1.0.0,<2.0.0, so its users get 1.1.0 on their next resolve. Both maintainers have accepted raising in 1.1.0, so this does not block. The 1.1.0 release notes should list these inputs under breaking changes.- 619b714 dropped the
(fields: ...)suffix, so two untitled models with the same nested field path, loaded from one line, now show one warning where 726726f showed two. Ondevthe schema path shows none. - Not re-run: the PR body's 2,112-cell parity sweep and its 488-config harvest, because their script is not in the repo.
Closes #334.
Refs #348 (items 2, 6 and 7; items 1 and 5 are deferred to 1.1.0).
Targets 1.1.0. It is a breaking change: some inputs that loaded on 1.0.x now raise
ValueError(see Breaking in 1.1.0), so it cannot ship in a patch release.Root cause
ComparableFieldrecords whether the author stated a threshold, clip or comparator (_threshold_explicit,_clip_explicit,_comparator_explicit). Two defaults key on those markers: adopting a threshold named on the comparator (#316) and the object-gradeclip_under_threshold=False(ConfigurationHelper.object_grade_clip).Both importers resolved their own defaults first (
threshold0.5 or the schema type default,clip_under_thresholdTrue) and passed concrete values, so every imported field read as "the author stated this" and neither default ever ran. #300 and #316 therefore landed on the Python path only.The change
field_converter.pyandjson_schema_importer.pypassNonefor a threshold or clip the author did not state, soComparableFieldresolves it as it does on the Python path.ExactComparator@1.0for an enum or date, a nested object's 0.7, an inferred value), the new private helper_mark_unstatedclears the marker on the field just built. The markers again mean "the author wrote this on the field".structured_model/optional_structured_model, or a schema object withpropertiesin all five spellings (inline,["object","null"],anyOfwith null,$ref,allOfwith$ref). A threshold the comparator names, incomparator_config/x-aws-stickler-comparator-configor in its own constructor, is read and gates the field, asComparableField(comparator=X(threshold=t))does. A named comparator stays on the field, as in Python, soexplain()reports it. It is never called. It, and any other config key, warns on both paths and points atthreshold/x-aws-stickler-threshold. When the comparator's threshold gates the field, the warning gives the value. On a list of models, comparator config is not read and warns, pointing atmatch_threshold. The comparator is rebuilt without the config'sthreshold, so that threshold does not reach the field, and its other keys are kept so a comparator that requires one still builds. A comparator that requiresthresholditself keeps the build from the full config, and its threshold stays off the field. Any other build failure there is aValueErrornaming the field. A comparator name on a list of models is unchanged, because Python itself is inconsistent there (Nested-model threshold resolution: list-of-models comparator names, and the unstated nested-object default (from #408) #468). A free-form{"type": "object"}still honours both keys.ValueErrorin 1.1.0 when the class is defined or the config or schema loads. It applies to the threshold a field ends up with, its own or one it adopts from its comparator, and tomatch_threshold. That covers the class (alsoModelFactory.create_model_from_fields(match_threshold=...)), the Stickler config and the JSON Schema. Before, the Python path checked none of them, and the importers acceptedtrueas 1 and never read a comparator-config threshold, so 85 there loaded at 0.5.Annotated[...]fields and a field whose type is defined further down the module. AnAnnotatedfield that names something defined further down, its type or a value in itsComparableField(...), is not yet checked at class definition when its annotation is a string, as every annotation is underfrom __future__ import annotations: pydantic holds it as one string untilmodel_rebuild(), so itsComparableFielddoes not exist yet. It loads as before (tracked as a follow-up).List["Later"]), the message says to remove the comparator ifLateris a model; a bare name for one (items: "ItemList") gets only the usual fix. An out-of-range field threshold on a visible list or on one name defined further down gets a fix for each case; on a dict or tuple of such a name it gets the usual fix. A PEP 695 alias is read as the type it names once the type it names is defined.threshold_rule.py. It quotes the value as written, names the model and the field, says why the value fails, spells out the fix, and on the Python path says where the value was set.Decimal,Fraction, numpy number or 0-d numpy array from 0.0 to 1.0 loads, converted withfloat(). A numpy float16 or float32 threshold ormatch_thresholdthen compares as a Python float, so a score within its rounding below it moves from TP to FD. Python kept such a value unconverted (aDecimalraisedTypeErroron any pair below it), and the importers refused it, except a numpy float64, which is afloatsubclass and loaded unconverted.match_thresholdofevaluate()andeval_for()keeps dev's check and message for a plain pydantic model, now on every call, and takes any real number from 0.0 to 1.0 converted withfloat()(aboolstill counts as 1.0 or 0.0, a numpy bool raises). AStructuredModel's value is not checked (tracked as a follow-up).List[StructuredModel]refusal ofComparableField(threshold=...)uses the same template: "has no effect on a List[Item] field ... Remove threshold=0.9", headedUnused thresholdwhatever the value, on all three paths. When the element class setsmatch_threshold, the fix says to set it and gives its current value, and never to keep a value it lacks. The warning for a comparator threshold there names the element class and points at the caller.model_name,x-aws-stickler-model-nameor the title. An unnamed model isof an unnamed model (set title or x-aws-stickler-model-name to name it)(config:set model_name), as in the errors, never theDynamicModel(fields: ...)warn-once identity.explain()trail.whynow names an adopted comparator threshold (config: comparator_config.threshold=0.9 (overrides above)). The schema path recorded no overrides at all. It now namesx-aws-stickler-threshold,-weightand-clip-under-thresholdoverrides as well.match_threshold: 0.0) was reported as "sets comparator threshold=0.0".Breaking in 1.1.0
Each of these loaded on 1.0.x and raises
ValueErroron this branch. Re-checked on0855590c(dev at v1.0.2) against619b7141."threshold": truein a config,x-aws-stickler-threshold: truein a schema (loaded as 1). Fix: write1.0.match_threshold = Trueon a class,"match_threshold": truein a config,x-aws-stickler-match-threshold: truein a schema (loaded as 1). Fix: write1.0.ComparableField(threshold=...)or a classmatch_threshold, which the Python path never checked (the importers already refused one in"threshold"and"match_threshold"). Fix: a number from 0.0 to 1.0, such as 0.85.LevenshteinComparator(threshold=85)in Python or"comparator_config": {"threshold": 85}in a config or schema (the importers never read it). Also on a list of models whose type is defined further down the module.thresholdas a distance or count, such as"comparator_config": {"threshold": 5}on an edit-distance comparator: the field now adopts 5.For a comparator threshold, the fix is to set the field's own
threshold(ComparableField(threshold=...),"threshold"orx-aws-stickler-threshold). It wins, and the comparator's is then neither adopted nor checked.Precedence
A threshold resolves as: field threshold, then a threshold named on the comparator, then the path's default (inferred value, schema type default, or 0.5). This is the Python rule from #316. A comparator threshold outranks an inferred one because the author wrote it and inference only guessed. A comparator's own default threshold is still never adopted (see
_named_comparator_threshold). The resolved threshold must be a number from 0.0 to 1.0.Before and after
Measured with
sticklerimported from each tree, Python 3.12. "dev" is8c56dfa6; the dev commits merged since change no threshold code. The config and schema columns of the first eight rows were measured on6e51532against434631cand re-measured onff19b01aagainst8c56dfa6, and they match. The classmatch_threshold = np.float32(0.9)row was measured on3a188580against6f762364, and the custom-constructor row on43579b11against6f762364. The rest were measured ond77fb56band8c56dfa6, for an identical pair unless stated.str, Levenshtein, comparatorthreshold: 0.9, no field threshold;ACME-1000vsACNE-1009(0.7778)threshold: 0.6comparator: "auto"plus comparatorthreshold: 0.9Dict[str, Any]naming ANLS*, 2 of 3 keys wrongList[Dict[str, Any]]naming ANLS*, same pairthreshold: 0.8on an object withpropertiesexplain()says explicitpropertiesexplain()says explicitthreshold: 85, no field thresholdthreshold: truethreshold: 85match_threshold = 85,Order(items=[Item(sku='a')])threshold: Decimal("0.9")(a config or schema dict built in Python); identical pair, thenACME-1000vsACNE-1009TypeError; branch: thr 0.9, 1.0, then 0.0 FDmatch_threshold = np.float32(0.9), a list item scoring 0.89999997 (ornp.float16(0.9)at 0.8998)threshold=np.float32(0.9), a score of 0.89999997 (ornp.float16(0.9)at 0.8998)addr: Address/tags: List[Color](an Enum), type defined later, threshold 85items: List["Later"], model defined later,LevenshteinComparator(threshold=85)evaluate(plain, plain, match_threshold=False)threshold=0.95tosuper(), no field threshold;'a'vs'b'(0.9)enum: 1.0, FD)Fields that state a valid threshold and clip are unchanged on every path, except a numpy float16 or float32 threshold or
match_thresholdas above. Measured on6e51532: a parity sweep over 12 field types (str, int, float, bool, date, enum, dict,List[str],List[dict], nested, optional nested,List[StructuredModel]) crossed with comparator, comparator threshold, field threshold, clip,infer-unspecifiedand classmatch_threshold(2,112 importer cells): 496 cells move to the Python result, 0 regress. What still differs is pre-existing and documented: schemaenum/constand thedateformats with a named comparator and no threshold resolve the documented 1.0 type default against Python's 0.5; the free-form-object threshold of 1.0 (#348 item 1); and the unstated nested-object default of 0.7 (#468). One cell to expect on a re-sweep: a schema array of objects withx-aws-stickler-comparator-config: {"threshold": 0.9}now reports threshold 0.5 where dev reported 0.9. That threshold is not used for scoring (the field score and confusion matrix are identical), and it now matches the config path.Round trips:
to_json_schema()andto_stickler_config()export resolved values, so clearing the markers changes no export. Every case re-imports to the same threshold, clip and score, and to the same comparator except on a nested model: neither exporter writes a nested model's named comparator, so it re-imports as theLevenshteinComparatorplaceholder, which is never called. The other exceptions are the dict shapes, which are already broken on dev: they export asstring(#348, adjacent finding). Schemas exported by v0.5.0 to v1.0.0to_json_schema(), and pydanticmodel_json_schema(), still import, because no exporter writes a comparator key on a nested object. Measured on6e51532, before the threshold check: every one of 488 configs and schemas harvested from the dev test suite, docs, READMEs, notebooks and examples that loaded on dev loaded there too, and exports from v0.5.0, v0.7.0 and v1.0.0 loaded with no new warning. Not re-run since; a harvested input with a threshold ormatch_thresholdoutside 0.0 to 1.0,trueor a string would now raise.Docs
docs/docs/Getting-Started/thresholds-and-metrics.md: a Valid Threshold Values section (what is valid, where it is checked, the message, what is not checked, and how a field whose type is defined further down is read) and a valid-values line for each threshold. The runtimematch_thresholdis outside the rule, with what each kind of model does.docs/docs/Guides/Evaluation/README.md: the extension table and the threshold defaults now cover comparator-config adoption, the threshold rule, the clip default for free-form objects, and the nested-model comparator warning (also in the troubleshooting table). The nested-object default is stated as a fixed 0.7.docs/docs/Advanced/dynamic-models.md: the same for the schema table and for config fields, and the new error messages in the troubleshooting table.docs/docs/Guides/Comparators/README.md: the rule for an adopted comparator threshold, with the Python message.README.md:x-aws-stickler-thresholddefault and rule, and the clip default.src/stickler/structured_object_evaluator/README.md: the extension defaults, and how the Python path checks the rule.from_json_schemaandmodel_from_jsondocstrings: the new defaults, the rule and the warning.CHANGELOG.md: both entries are under[Unreleased], above the shipped[1.0.2]. The threshold/clip entry (Changed) says the check raisesValueErrorin 1.1.0, lists the inputs that loaded on 1.0.x and now raise with the fix, and which verdicts move. The comparator-on-object entry is under Fixed.Tests
tests/structured_object_evaluator/test_importer_resolution_parity.py(new, 65 tests) checks the three paths against Python wherever they are meant to agree. It covers threshold adoption, including on a nested model and from a custom comparator's constructor on a scalar and a nested model; the clip default for a dict and a list of dicts; unstated defaults surviving; the markers; theexplain()trail and comparator; the warning wording, model name (an unnamed model named as the errors name it) and stacklevel; the array-of-objects rebuild and its fallback; and the union-of-objects behaviour.tests/structured_object_evaluator/test_threshold_validation.py(new, 536 tests) covers:Decimal,Fraction, numpy number or 0-d array loads asfloat()gives it, and a numpy float16 or float32 threshold ormatch_thresholdcompares as that float.match_threshold, also from 0.0 or when there is no value to move. A dict or tuple of a type defined further down gets the usual fix.match_thresholdkeeps its own check, takes any real number in range as a float on every call, andFalsedoes not warn.Annotatedfields, postponed annotations and exports load.test_object_property_threshold.py:TestTheComparatorOnTheSameNodeIsStillDroppedbecomesTestTheComparatorOnTheSameNodeWarns(11 tests: five schema spellings plus the free-form contrast).srcreverted to its parent.Full suite at
619b7141, Python 3.12,sticklerimported from this branch: 6099 passed, 13 skipped, 1 xfailed, plustests/test_docs_build.pyandtests/test_readme_examples.py88 passed.ruff check .is clean.Since
726726f3:f0800a44merges dev (v1.0.2 and fix(json-schema): read model keys on nullable objects, check $defs entries, flag model keys no class reads #407). See Note for reviewers.b78859fb: dev's report test builtComparableField(threshold=nan), which now raises. It patches the extracted thresholds instead, since the report still drops a non-finite one (a stringAnnotatedannotation naming a later type still loads one).e7ccbdcarenamestest_bool_is_not_reported_as_a_zero_thresholdtotest_bool_threshold_is_refused_not_reported_as_zero, which is what it asserts.619b7141names the model in the nested-model warnings as the errors do (see The change).Changes in results
Items 1 and 2 are fixes: the importers now do what the docs and the Python path already do. Item 3 is breaking (see Breaking in 1.1.0).
comparator_config/x-aws-stickler-comparator-configor by a custom comparator's constructor, now gates the field when no field threshold is stated, including on a nested model and over an inferred threshold or a schema type default (1.0 for an enum or date). No built-in comparator sets one when built bare, so fields naming one do not move.clip_under_threshold: trueon either importer, so ANLS* partial credit below the threshold is kept. An explicittrueis still honoured.match_thresholdthat is not a number from 0.0 to 1.0 now raises on load, on the class, the config and the schema. Before, on the Python path it scored: a field threshold of 85 scored an identical pair 0.0, and a classmatch_thresholdof 85 made every list pair an FD. On the importerstrueloaded as 1 and a comparator-config threshold was not read. On a list of models defined further down, an out-of-range comparator threshold now raises too, though it was never read. An in-rangeDecimal,Fractionor numpy threshold other than a float64 now loads on the importers, which refused it, and aDecimalon the Python path no longer raisesTypeErrorwhen a pair scores below it. A numpy float16 or float32 threshold ormatch_thresholdcompares as a Python float, so a score within its rounding below it is an FD where it was a TP. The runtimematch_thresholdofevaluate()andeval_for()keeps its own check, and on a plain model now takes an in-rangeDecimal,Fractionor numpy number as a float.Comparator keys a nested model does not read now warn instead of being dropped or refused.
Note for reviewers
dev at
0855590c(v1.0.2, including #407) is merged in atf0800a44. Conflicts:json_schema_importer.py: one_make_comparison_field(...)call. Kept fix(json-schema): read model keys on nullable objects, check $defs entries, flag model keys no class reads #407'sfield_path=field_pathand this branch'scomparator=placeholder; the signature takes both.CHANGELOG.md: dev's file unchanged, with this PR's two entries moved under[Unreleased].docs/docs/Guides/Evaluation/README.md: the schema extension table keeps this branch's comparator, threshold-range and comparator-config text and dev'sList[StructuredModel]note, inference clip note and infer-unspecified wording.tests/structured_object_evaluator/README.md: both paragraphs.