Repository navigation
fix(391): score tuple and set fields as one value - #688
Conversation
- widen the list-of-tuples predicate to a tuple, set or frozenset field, or a list of one, so all take the install path at class definition and the export names ExactComparator - test the origin as a subclass, so a NamedTuple or AbstractSet field counts too - mark the last-resort substitution explicit, as the install path does, so a tuple or set pair reaches the comparator in both readers, and test it through a forward reference resolved by model_rebuild() - give a bare tuple or set annotation the same comparator - a comparator named with comparator= is never replaced - flip the guard that kept a tuple field on Levenshtein
- send a tuple or set pair under an inferred comparator through scalar_pair_comparator in compare(), as compare_with() does - with an inferred comparator, two tuples or two sets go to ExactComparator, so an Any or Sequence[int] field scores them as a Tuple or Set field does, at the top level, on a nested model and in a list-of-models item - a dict view is not a set here, so it keeps its rule from before - with an inferred comparator, compare() now scores a tuple against a list or a set as 0.0, as compare_with() does - a declared comparator is called on the same pairs as before in both readers, a tuple against a list in compare() included
- no partial credit; point to PointDistanceComparator, BBoxIoUComparator or a custom comparator for tolerance - note that a Tuple[str, str] loses per-string partial credit - note that a tuple compares by its printed text and a set by membership in any order, and that a set or array inside a tuple is printed too - note that NamedTuple and AbstractSet fields follow the same rule, and so do two tuples or two sets in an Any or Sequence field - note that with no comparator named a tuple against a list or a set scores 0.0, and that List[Any] elements keep the list's comparator
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-12-03T15:45:01+00:00 |
mangeshraut712
left a comment
There was a problem hiding this comment.
I ran this against dev (33ed6c3) because it builds on #669/#670, which I authored. Everything below is from running the branch, not from reading it. Not an approval — that's for a maintainer — just the numbers.
What I confirmed
-
src/stickler/comparators/exact.pyis byte-identical todev, so #669's set-by-membership path is untouched. -
Full suite on the branch:
7187 passed, 13 skipped, 1 xfailed— matches the description exactly. -
The new test file has teeth: dropped onto
devit gives79 failed, 25 passed. So 79 of the 104 tests pin behaviour that is actually broken today. -
The core #391 contradiction is real on
devand fixed here. On anAnyfield holding two identical tuples,devgivescompare()= 1.000 andcompare_with()= 0.000. On the branch both give1.000. Same for identical sets. -
The mismatch rule in the description holds, and
devwas worse than "edit distance" suggests. On anAnyfield:pair devcompare()branch compare()compare_with()tuple vs list 0.667 0.000 0.000 tuple vs set 0.353 0.000 0.000 set vs list 0.235 0.000 0.000 A tuple against a list scored two-thirds on
dev. Both readers now agree at0.0.
The disclosed hash-seed limitation, with a concrete reproducer
Your "not covered" note is accurate. Tuple[FrozenSet[str], int] with frozenset({"x","y"}) on both sides, via compare_with(), across PYTHONHASHSEED:
seed: 0 1 2 3 5 42
score: 1.0 0.0 1.0 0.0 1.0 1.0
Two identical values flip between match and mismatch on the seed. The top-level Set[str] and FrozenSet[int] fields are stable at 1.0 across all six seeds, so test_the_verdict_does_not_depend_on_the_hash_seed covers what it claims. I'd only suggest adding the nested case as an xfail with the seed table in a comment, so the boundary is executable rather than prose — but that's a nit and your call.
On your question to @sromoam about members keeping their type (1 / 1.0 / True differing inside a tuple): that is consistent with how ExactComparator behaves on dev today, so the PR isn't introducing a new strictness. I'll leave the design answer to him.
One small wording note on the description: "a tuple against a list or a set now scores 0.0 in compare()" is correct for Any-typed fields, but it can't arise on a Tuple[...]-annotated field, since Pydantic coerces [1, 2] to a tuple before comparison. Worth a half-sentence so a reader doesn't try to reproduce it on an annotated field and get 1.0.
sromoam
left a comment
There was a problem hiding this comment.
Thanks Diego. The rule works. On this head, identical tuple and set fields score 1.0 in both readers, and swapped tuples score 0.0. On a 60 x 60 list of 20-field rows with a tuple field, it's faster than dev (6.8 s against 7.8 s), so the per-call checks cost nothing measurable. One fix before merge.
Must fix: an ItemsView field now crashes. _names_exact_collection matches every collections.abc.Set subclass, and dict views are among them. So f: ItemsView = ComparableField() gets ExactComparator, whose set branch hashes the members. With unhashable values, M(f={"k": [1]}.items()) against itself raises TypeError: unhashable type: 'list' from both compare() and compare_with(). On dev both returned 0.0. _same_kind_of_collection already leaves dict views out for exactly this reason, so the annotation rule should match it. Excluding collections.abc.MappingView there would do it (inline). A KeysView field then goes back to dev's behaviour too; it scores 1.0 on this head.
Your question: yes to both. Members keep their type, as ExactComparator and #669 already do, so 1, 1.0 and True differ inside a tuple. A typed field is coerced by pydantic before scoring anyway, so this only matters for Any. Applying the rule by value, so an Any field holding tuples is covered, is right.
Filed as follow-ups, not for this PR:
- #717: tuples and sets inside a
List[Any]still go through Levenshtein ([(1, 2)]vs[(2, 1)]scores 0.667). - #718: for an
Anyfield, the reported comparator still says Levenshtein when a tuple pair is scored exactly. - #719: with an explicit comparator,
compare()andcompare_with()still disagree on a tuple against a list.
| # subclass test, because a NamedTuple is its own origin and | ||
| # `AbstractSet` reports `collections.abc.Set`. | ||
| origin = get_origin(annotation) or annotation | ||
| return isinstance(origin, type) and issubclass(origin, (tuple, abc_Set)) |
There was a problem hiding this comment.
A dict view is an abc.Set too, but its members need not be hashable, which is why _same_kind_of_collection leaves it out. Matching that here keeps the annotation rule and the value rule in step (needs from collections.abc import MappingView):
| return isinstance(origin, type) and issubclass(origin, (tuple, abc_Set)) | |
| return ( | |
| isinstance(origin, type) | |
| and issubclass(origin, (tuple, abc_Set)) | |
| and not issubclass(origin, MappingView) | |
| ) |
- a dict view or a user collections.abc.Set subclass is an abstract set whose members need not be hashable, so an ItemsView of lists raised TypeError in compare() and compare_with(); dev scored 0.0 - the annotation rule now matches _same_kind_of_collection: tuple, set, frozenset and their subclasses, plus AbstractSet and MutableSet, which pydantic stores as sets
|
Thanks @sromoam. Fixed in Excluding
Thanks for filing #717, #718 and #719, and for the answer on member types. |
sromoam
left a comment
There was a problem hiding this comment.
Thanks Diego, and thanks for going past the suggestion. On 16a5ca13 an ItemsView field scores 0.0 in compare(), compare_with() and compare_field_raw(), with no TypeError. KeysView, Optional[ItemsView], List[ItemsView] and your Bag case all match dev again. Every tuple and set shape this PR is for scores exactly as on the previous head, and the new tests fail there and pass here.
To get it into 1.1.0, I pushed the dev merge myself as ce2e8f22. The only conflict was the comment block in _install_object_grade_comparators: dev's List[StructuredModel] clip block from #627 now comes first, then your comment wording. On the merge, the full suite gives 7398 passed, 13 skipped, 1 xfailed, and ruff check . and docs/check_links.py are clean. Approving.
Tiny, optional: the comment that says pydantic stores a set for an AbstractSet field should say frozenset, which is what it stores.
tl;dr for humans
This fixes #391. A
Tuple,SetorFrozenSetfield with no comparator named scored0.0against an identical value incompare_with(), whilecompare()scored edit distance over the repr. Now both inferExactComparatorand score1.0for equal values and0.0otherwise, and the export namesExactComparator. The rule also applies by value: when the comparator is inferred and both values are tuples, or both are sets, the pair scores byExactComparator, so anAnyorSequence[int]field holding(1, 2)on both sides scores1.0in both readers, wherecompare_with()gave0.0. A comparator named withcomparator=is never replaced and gives the same scores as before, andList[str],stranddictscores do not change.ExactComparatoritself is unchanged: it compares two tuples by their printed text and two sets by membership (#669), the same path #670 uses forList[Tuple].@sromoam, one question. Members keep their type, as
ExactComparatordoes today, so1,1.0andTruediffer inside a tuple. And the rule applies by value, soAnyfields holding tuples are covered. Does that match what you meant?for agents
ExactComparatoras it is ondev, and a tuple or set field takes the install path fix: score a tuple in a list as one value, not by its repr #670 added for a list of tuples.Tuple,Set,FrozenSet,NamedTupleorAbstractSetfield, bare or in aList, with nocomparator=, infersExactComparatorat class definition, socompare(),compare_with()andevaluate()agree.()against()is a true positive. AgainstNoneit is a false negative.Tuple[float, float]converts members first, so(1, 2)matches(1.0, 2.0). ATuple[str, str]loses per-string partial credit:("Acme Corp", "NY")against("Acme Corporation", "NY")is0.0.AnyorSequence[int]with nocomparator=scores two tuples, or two sets, byExactComparatortoo, at the top level, on a nested model and in a list-of-models item. Two identical tuples there scored0.0incompare_with()and1.0incompare(). Tuples or sets inside aList[Any]still use the list's comparator. A dict view is not treated as a set there, so it keeps its score from before.0.0incompare(), as incompare_with();compare()gave edit distance over the repr.to_stickler_config()andto_json_schema()nameExactComparator.ExactComparatorincluded, is called on the same pairs as before and gives the same score in both readers. Over 8 declared comparators, 8 annotations and 27 pairs (top level andList[Any],PYTHONHASHSEED0 to 3),compare()andcompare_with()equaldevon every row.src/stickler/structured_object_evaluator/models/configuration_helper.py:_names_exact_collectionand_is_exact_collection_fieldreplace_is_list_of_tuples, and the predicate isissubclass(origin, (tuple, abc_Set)).get_comparison_infomarks the last resort substitution explicit, as the install path does.src/stickler/structured_object_evaluator/models/structured_model.py: the install path calls_is_exact_collection_field.src/stickler/structured_object_evaluator/models/comparison_helper.py: keeps the_COLLECTIONSbranch incompare_field_rawfor a declared comparator only.scalar_pair_comparatorreplacesscalar_pair_reaches_comparatorand returns the comparator that scores a pair, orNonefor a mismatch: the declared one,ExactComparatorfor two tuples or two sets under an inferred one, else the inferred one where it can be trusted.ComparisonDispatcher(CASE 1) andcompare_field_rawboth read it;FieldComparator.compare_primitive_with_scorestakes the chosen comparator.docs/docs/Guides/Comparators/README.md. CHANGELOG: the Tuple and Set fields score 0.0 against an identical value in compare_with(), and compare() disagrees #391 bullet at the end of### Fixedunder[Unreleased], plus a one-line edit to the [BUG]: tuple elements in a List are scored by Levenshtein over their repr #659 bullet from fix: score a tuple in a list as one value, not by its repr #670.fix(391): infer ExactComparator for tuple and set fields: patch, corrects thecompare_with()score.fix(391): score tuple and set values by one rule in both readers: patch, makescompare()agree and scores tuple and set values inAnyandSequencefields.docs(391): say an inferred comparator compares a tuple or set exactly: no behavior change.uv run --frozen pytest -qafter each commit. Ondevwith this series:7187 passed, 13 skipped, 1 xfailed, andtests/integrationsgives 690 passed, 1 skipped.tests/structured_object_evaluator/test_collection_field_inference.py.test_the_verdict_does_not_depend_on_the_hash_seedpins aSet[str]field across seeds.test_a_forward_reference_resolved_later_is_inferred_toocoversmodel_rebuild().1.0in both readers forPYTHONHASHSEED0 to 5.src/stickler/comparators/exact.pyis unchanged fromdev.uv lock --check,ruff checkanddocs/check_links.pypass.ExactComparatorondevand as fix: score a tuple in a list as one value, not by its repr #670'sList[Tuple]:Tuple[FrozenSet[str], int], compares by its printed text, so the score depends onPYTHONHASHSEED.Anyfield,(np.float64(1.0), 2.0)does not match(1.0, 2.0). A typed field such asTuple[float, float]converts the member first and matches.(-0.0, 1.0)does not match(0.0, 1.0).model_rebuild()resolves a forward reference,to_stickler_config()still namesLevenshteinComparatorfor that field, even though scoring usesExactComparator. The fix: score a tuple in a list as one value, not by its repr #670 list of tuples has the same gap. A follow-up that reruns the install on rebuild would fix it.0.0incompare_with()and the comparator's score incompare():PointDistanceComparator(max_distance=1.0)on(1.0, 2.0)against[1.0, 2.0]gives0.0and1.0. This was already so before this change, and I left it for a follow-up issue.AnyorSequence[int]field exports as"type": "str"with a warning, somodel_from_json(to_stickler_config())rejects a tuple value before any comparator runs. This was already so before this change.Any,Optional[Any]andSequencefields,evaluate()dumps tuples to JSON lists and pairs them order-free, so(1, 2)against(2, 1)is1.0there and0.0incompare()andcompare_with(). This was already so before this change.Sequence[Any],(1, 2)against(2, 1)gavecompare()0.667andcompare_with()0.0ondev; with this series both give0.0, where [BUG]: a tuple value in a Sequence field scores differently from the same value as a list #664 expects the list score1.0. ItsBBoxIoUComparatorrows keep theirdevscores: the tuple against the equal list is still1.0incompare()and0.0incompare_with(), and()againstNoneis still a false negative.Closes #391