Skip to content

fix(391): score tuple and set fields as one value - #688

Merged
digalaviz merged 5 commits into
awslabs:devfrom
digalaviz:fix/391-collection-one-value
Dec 3, 2026
Merged

digalaviz merged 5 commits into
awslabs:devfrom
digalaviz:fix/391-collection-one-value

Conversation

@digalaviz

Copy link
Copy Markdown
Contributor

tl;dr for humans

This fixes #391. A Tuple, Set or FrozenSet field with no comparator named scored 0.0 against an identical value in compare_with(), while compare() scored edit distance over the repr. Now both infer ExactComparator and score 1.0 for equal values and 0.0 otherwise, and the export names ExactComparator. The rule also applies by value: when the comparator is inferred and both values are tuples, or both are sets, the pair scores by ExactComparator, so an Any or Sequence[int] field holding (1, 2) on both sides scores 1.0 in both readers, where compare_with() gave 0.0. A comparator named with comparator= is never replaced and gives the same scores as before, and List[str], str and dict scores do not change.

ExactComparator itself is unchanged: it compares two tuples by their printed text and two sets by membership (#669), the same path #670 uses for List[Tuple].

@sromoam, one question. Members keep their type, as ExactComparator does today, so 1, 1.0 and True differ inside a tuple. And the rule applies by value, so Any fields holding tuples are covered. Does that match what you meant?


for agents

  • intent: Tuple and Set fields score 0.0 against an identical value in compare_with(), and compare() disagrees #391 asks that a tuple or set field score the same in both readers and against an identical value. A tuple or set is now one value under an inferred comparator, scored by ExactComparator as it is on dev, 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.
  • behavior:
    • A Tuple, Set, FrozenSet, NamedTuple or AbstractSet field, bare or in a List, with no comparator=, infers ExactComparator at class definition, so compare(), compare_with() and evaluate() agree.
    • () against () is a true positive. Against None it is a false negative.
    • Tuple[float, float] converts members first, so (1, 2) matches (1.0, 2.0). A Tuple[str, str] loses per-string partial credit: ("Acme Corp", "NY") against ("Acme Corporation", "NY") is 0.0.
    • A field typed Any or Sequence[int] with no comparator= scores two tuples, or two sets, by ExactComparator too, at the top level, on a nested model and in a list-of-models item. Two identical tuples there scored 0.0 in compare_with() and 1.0 in compare(). Tuples or sets inside a List[Any] still use the list's comparator. A dict view is not treated as a set there, so it keeps its score from before.
    • With an inferred comparator, a tuple against a list or a set now scores 0.0 in compare(), as in compare_with(); compare() gave edit distance over the repr.
    • to_stickler_config() and to_json_schema() name ExactComparator.
    • A declared comparator, ExactComparator included, 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 and List[Any], PYTHONHASHSEED 0 to 3), compare() and compare_with() equal dev on every row.
  • code:
    • src/stickler/structured_object_evaluator/models/configuration_helper.py: _names_exact_collection and _is_exact_collection_field replace _is_list_of_tuples, and the predicate is issubclass(origin, (tuple, abc_Set)). get_comparison_info marks 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 _COLLECTIONS branch in compare_field_raw for a declared comparator only. scalar_pair_comparator replaces scalar_pair_reaches_comparator and returns the comparator that scores a pair, or None for a mismatch: the declared one, ExactComparator for two tuples or two sets under an inferred one, else the inferred one where it can be trusted. ComparisonDispatcher (CASE 1) and compare_field_raw both read it; FieldComparator.compare_primitive_with_scores takes the chosen comparator.
    • Docs: the new "Tuples and sets" section in 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 ### Fixed under [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.
  • commits:
    • fix(391): infer ExactComparator for tuple and set fields: patch, corrects the compare_with() score.
    • fix(391): score tuple and set values by one rule in both readers: patch, makes compare() agree and scores tuple and set values in Any and Sequence fields.
    • docs(391): say an inferred comparator compares a tuple or set exactly: no behavior change.
    • Every commit passes the full suite on its own.
  • verification:
    • uv run --frozen pytest -q after each commit. On dev with this series: 7187 passed, 13 skipped, 1 xfailed, and tests/integrations gives 690 passed, 1 skipped.
    • New tests are in tests/structured_object_evaluator/test_collection_field_inference.py. test_the_verdict_does_not_depend_on_the_hash_seed pins a Set[str] field across seeds. test_a_forward_reference_resolved_later_is_inferred_too covers model_rebuild().
    • The Tuple and Set fields score 0.0 against an identical value in compare_with(), and compare() disagrees #391 repro gives 1.0 in both readers for PYTHONHASHSEED 0 to 5.
    • src/stickler/comparators/exact.py is unchanged from dev.
    • uv lock --check, ruff check and docs/check_links.py pass.
  • not covered:
    • Known limitations, the same as ExactComparator on dev and as fix: score a tuple in a list as one value, not by its repr #670's List[Tuple]:
      • A set inside a tuple, such as Tuple[FrozenSet[str], int], compares by its printed text, so the score depends on PYTHONHASHSEED.
      • In an Any field, (np.float64(1.0), 2.0) does not match (1.0, 2.0). A typed field such as Tuple[float, float] converts the member first and matches.
      • A numpy array inside a tuple compares by its printed text, so two arrays that print the same match, such as values that differ past numpy's print precision, or long arrays that differ only where numpy elides them.
      • (-0.0, 1.0) does not match (0.0, 1.0).
    • After model_rebuild() resolves a forward reference, to_stickler_config() still names LevenshteinComparator for that field, even though scoring uses ExactComparator. 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.
    • With a declared comparator, a tuple against a list scores 0.0 in compare_with() and the comparator's score in compare(): PointDistanceComparator(max_distance=1.0) on (1.0, 2.0) against [1.0, 2.0] gives 0.0 and 1.0. This was already so before this change, and I left it for a follow-up issue.
    • An Any or Sequence[int] field exports as "type": "str" with a warning, so model_from_json(to_stickler_config()) rejects a tuple value before any comparator runs. This was already so before this change.
    • For Any, Optional[Any] and Sequence fields, evaluate() dumps tuples to JSON lists and pairs them order-free, so (1, 2) against (2, 1) is 1.0 there and 0.0 in compare() and compare_with(). This was already so before this change.
    • [BUG]: a tuple value in a Sequence field scores differently from the same value as a list #664 stays open. In Sequence[Any], (1, 2) against (2, 1) gave compare() 0.667 and compare_with() 0.0 on dev; with this series both give 0.0, where [BUG]: a tuple value in a Sequence field scores differently from the same value as a list #664 expects the list score 1.0. Its BBoxIoUComparator rows keep their dev scores: the tuple against the equal list is still 1.0 in compare() and 0.0 in compare_with(), and () against None is still a false negative.

Closes #391

- 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
@digalaviz
digalaviz requested a review from sromoam as a code owner December 1, 2026 00:55
@digalaviz digalaviz added this to the 1.1.0 milestone Dec 1, 2026
@digalaviz
digalaviz requested a review from vawsgit December 1, 2026 00:55
@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-12-03T15:45:01+00:00
  • Time since scan: 3 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-12-03T15:41:26+00:00
  • ASH version: 3.1.2

Summary

Scanner Results

The table below shows findings by scanner, with status based on severity thresholds and dependencies:

  • Severity levels:
    • Suppressed (S): Findings that have been explicitly suppressed and don't affect scanner status
    • Critical (C): Highest severity findings that require immediate attention
    • High (H): Serious findings that should be addressed soon
    • Medium (M): Moderate risk findings
    • Low (L): Lower risk findings
    • Info (I): Informational findings with minimal risk
  • Duration (Time): Time taken by the scanner to complete its execution
  • Actionable: Number of findings at or above the threshold severity level that require attention
  • Result:
    • PASSED = No findings at or above threshold
    • FAILED = Findings at or above threshold
    • MISSING = Required dependencies not available
    • SKIPPED = Scanner explicitly disabled
    • ERROR = Scanner execution error
  • Threshold: The minimum severity level that will cause a scanner to fail
    • Thresholds: ALL, LOW, MEDIUM, HIGH, CRITICAL
    • Source: Values in parentheses indicate where the threshold is set:
      • global (global_settings section in the ASH_CONFIG used)
      • config (scanner config section in the ASH_CONFIG used)
      • scanner (default configuration in the plugin, if explicitly set)
  • Statistics calculation:
    • All statistics are calculated from the final aggregated SARIF report
    • Suppressed findings are counted separately and do not contribute to actionable findings
    • Scanner status is determined by comparing actionable findings to the threshold
Scanner Suppressed Critical High Medium Low Info Actionable Result Threshold
bandit 0 0 0 0 8120 0 0 PASSED MEDIUM (global)
cdk-nag 0 0 0 0 0 0 0 PASSED MEDIUM (global)
cfn-nag 0 0 0 0 0 0 0 MISSING MEDIUM (global)
checkov 0 0 0 0 0 0 0 PASSED MEDIUM (global)
detect-secrets 0 0 0 0 0 0 0 PASSED MEDIUM (global)
grype 0 0 0 0 0 0 0 MISSING MEDIUM (global)
npm-audit 0 0 0 0 0 0 0 PASSED MEDIUM (global)
opengrep 0 0 0 0 0 0 0 MISSING MEDIUM (global)
semgrep 7 0 0 0 0 0 0 PASSED MEDIUM (global)
syft 0 0 0 0 0 0 0 MISSING MEDIUM (global)

Report generated by Automated Security Helper (ASH) at 2026-12-03T15:45:01+00:00

@mangeshraut712 mangeshraut712 left a comment

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.

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.py is byte-identical to dev, 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 dev it gives 79 failed, 25 passed. So 79 of the 104 tests pin behaviour that is actually broken today.

  • The core #391 contradiction is real on dev and fixed here. On an Any field holding two identical tuples, dev gives compare() = 1.000 and compare_with() = 0.000. On the branch both give 1.000. Same for identical sets.

  • The mismatch rule in the description holds, and dev was worse than "edit distance" suggests. On an Any field:

    pair dev compare() 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 at 0.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 sromoam left a comment

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.

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 Any field, the reported comparator still says Levenshtein when a tuple pair is scored exactly.
  • #719: with an explicit comparator, compare() and compare_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))

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.

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):

Suggested change
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
@digalaviz

Copy link
Copy Markdown
Contributor Author

Thanks @sromoam. Fixed in 16a5ca13, and it goes one step past the suggestion.

Excluding MappingView removed the ItemsView crash, but the same crash remained for a user class built on collections.abc.Set with unhashable members (with arbitrary_types_allowed): Bag([[1]]) against itself raised TypeError: unhashable type: 'list' in both readers, where dev scored 0.0. So the annotation rule now matches _same_kind_of_collection exactly: tuple, set, frozenset and their subclasses, plus AbstractSet and MutableSet, which pydantic stores as sets. Any other abstract set keeps its rule from before.

  • Every case this PR exists for scores the same as the previous head: tuple, Tuple[int, int], Optional[Tuple], a NamedTuple, set, Set[int], FrozenSet[int], AbstractSet[int], collections.abc.Set[int], MutableSet[int], a set subclass and List[Tuple] (1.0 equal, 0.0 swapped).
  • ItemsView, KeysView and the user abstract set score 0.0 in both readers, as on dev, with no TypeError.
  • Tests: test_a_dict_view_annotation_keeps_its_rule (ItemsView, KeysView) and test_a_user_abstract_set_annotation_keeps_its_rule in test_collection_field_inference.py; all three fail on the previous head.
  • Full suite: 7190 passed, 13 skipped, 1 xfailed.

Thanks for filing #717, #718 and #719, and for the answer on member types.

@digalaviz
digalaviz requested a review from sromoam December 2, 2026 01:54

@sromoam sromoam left a comment

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.

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.

@digalaviz
digalaviz merged commit 104b768 into awslabs:dev Dec 3, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Tuple and Set fields score 0.0 against an identical value in compare_with(), and compare() disagrees

3 participants