Skip to content

fix: raise ValueError for an unknown FuzzyComparator method - #647

Open
pcbeingused33 wants to merge 9 commits into
awslabs:devfrom
pcbeingused33:bugfix/fuzzy-unknown-method
Open

pcbeingused33 wants to merge 9 commits into
awslabs:devfrom
pcbeingused33:bugfix/fuzzy-unknown-method

Conversation

@pcbeingused33

@pcbeingused33 pcbeingused33 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Issue Reference

No tracking issue.

Description of Changes

FuzzyComparator accepted any method string and silently used fuzz.ratio for the ones it did not know. It now raises ValueError and lists the accepted names. A non-string method raises the same ValueError instead of TypeError.

Changes Made

  • Reject an unknown method in FuzzyComparator.__init__ instead of .get(method, fuzz.ratio), and reject a non-string before the lookup
  • The scenario tests no longer construct a second ratio comparator as fuzzy_weighted. Those assertions use fuzzy_ratio
  • Regression test and CHANGELOG.md entry

Why These Changes Are Needed

A misspelled name such as "token_sort" scored with plain ratio, while name and config still reported token_sort. PhoneComparator already raises ValueError for an unknown region.

Reproduction

c = FuzzyComparator(method="token_sort")
c.name                                   # "fuzzy_token_sort"
c.compare("john smith", "smith john")    # 0.5, the plain ratio; token_sort_ratio gives 1.0

Testing

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing completed
  • All existing tests pass

The unknown-method cases fail on dev and pass with the change. The seven cases in tests/structured_object_evaluator/test_comparator_scenarios.py pass after removing the duplicate comparator. tests/common plus tests/structured_object_evaluator were 5171 passed and 2 skipped on an earlier commit of this branch; that slice was not re-run for this test-only edit.

Checklist

  • Code follows the project's coding standards
  • CHANGELOG.md entry added under [Unreleased]
  • Tests added/updated for new functionality

Additional Notes

Code or configs that pass an unrecognized name will now fail at construction. If weighted_ratio is meant to be supported (as fuzz.WRatio), that would change scores for anyone passing it today, so it is not part of this change. This edit does not change scores: it only stops the scenarios from presenting a second ratio comparator as a weighted method.

This change was prepared with AI assistance (Claude Code).

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@vawsgit vawsgit 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.

✅ LGTM!

Comment thread CHANGELOG.md Outdated

### Fixed

- `FuzzyComparator` raises `ValueError` for an unknown `method` instead of

@vawsgit vawsgit Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: an unknown method used to load and score as ratio, and now it fails at construction, on the Python path and in configs. On this head, from_json_schema() raises Invalid x-aws-stickler-comparator 'FuzzyComparator' in field 'n': Unknown fuzzy method 'token_sort', and model_from_json() raises too. The closest [Unreleased] entry is #607 (model_from_json() now raises for match_threshold on a primitive field, where 1.0.x warned), and it sits under ### Changed, not ### Fixed. Moving this entry there, or marking it **Breaking:** as #646 does, would make it show in the release notes as a change users must act on.

…gelog

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@pcbeingused33

Copy link
Copy Markdown
Contributor Author

Moved the entry to ### Changed, after the #607 one, in 2774d3f. Only CHANGELOG.md changed.

This comment was drafted with Claude Code.

@vawsgit vawsgit 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.

✅ LGTM!

@digalaviz

Copy link
Copy Markdown
Contributor

Thanks! One more case while you're here: a non-string method such as ["ratio"] or a dict still raises TypeError: unhashable type, because method not in fuzzy_funcs hashes it first. Could you check isinstance(method, str) before the lookup, so it raises the same ValueError? #667 did the same for AngleComparator(angle_unit=...).

@pcbeingused33

Copy link
Copy Markdown
Contributor Author

Thanks, Diego. In cb6a53a, FuzzyComparator checks that method is a string before looking it up. A list or dict now raises the same ValueError as an unknown name. Both inputs have regression coverage.

This comment was drafted with AI assistance (Codex).

@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.

Tested the PR head (c1f7e3411) in a clean worktree.

Result: 32/32 pass across test_comparators.py + test_comparator_scenarios.py. Teeth confirmed: all 5 new parametrized cases fail on main with DID NOT RAISE <class 'ValueError'>.

I also drove the constructor against 14 method shapes on both main and the PR. The thing that makes this more than a "fail loudly on a typo" fix is what main does with the comparator's name:

=== main ===
'token_sort'      -> SILENT fallback, name='fuzzy_token_sort'
'weighted_ratio'  -> SILENT fallback, name='fuzzy_weighted_ratio'
''                -> SILENT fallback, name='fuzzy_'
None              -> SILENT fallback, name='fuzzy_None'
1                 -> SILENT fallback, name='fuzzy_1'
b'ratio'          -> SILENT fallback, name="fuzzy_b'ratio'"
['ratio']         -> TypeError: unhashable type: 'list'
{'method': ...}   -> TypeError: unhashable type: 'dict'

name is f"fuzzy_{self._method}" (line 84) — the requested method — while _fuzzy_func was silently set to fuzz.ratio. So on main, anyone who asked for weighted_ratio got ratio scoring, and every result, report or comparison detail that carries the comparator name said fuzzy_weighted_ratio. In an evaluation framework that's a mislabelled score, not just an ignored argument. The TypeError shapes were also opaque (unhashable type) rather than pointing at the bad value.

On the PR all 14 produce the same clear ValueError naming the valid options, including the non-string ones thanks to the isinstance guard before the dict lookup. The scenario test's weighted_ratio → ratio rename is correct and score-neutral: main was already computing ratio under that name, and the test only touches the constructor.

One design question for the maintainer, not a blocker. The scenario test is evidence that someone expected weighted_ratio to exist, and rapidfuzz.fuzz does ship it as fuzz.WRatio (verified on rapidfuzz 3.14.3). Rejecting it is the right call for a PR whose purpose is "stop silently substituting", and I'd keep this PR as-is. But a follow-up adding "weighted_ratio": fuzz.WRatio would turn a now-rejected name into a working option, and it's a one-line addition to fuzzy_funcs. The same applies to "token_sort" as an alias for token_sort_ratio — whether aliases are wanted is a maintainer preference.

Minor: the isinstance(method, str) check means a bytes method like b"ratio" is rejected rather than decoded. That's the right default (it's a type error in the caller), just noting it's deliberate.

The docstring Raises: addition and the CHANGELOG entry are both clear. LGTM.

@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 @pcbeingused33, this is a clean fix. On c1f7e341 Diego's non-string check and the CHANGELOG move from vawsgit's note are both in, and an unknown method now raises from Python, from a Stickler config (top level, structured_model and list_structured_model) and from x-aws-stickler-comparator-config. It merges cleanly with current dev, and the full suite passes on the merge.

Smaller

  1. fuzzy_weighted is now a second ratio comparator (tests/structured_object_evaluator/test_comparator_scenarios.py:28), so the scenarios read as if a weighted method were covered. Details inline.

One heads-up: we're not merging anything outside the 1.1.0 milestone until 1.1.0 lands, so this will wait until after that even once it's ready.

self.fuzzy_token_set = FuzzyComparator(method="token_set_ratio")
self.fuzzy_partial = FuzzyComparator(method="partial_ratio")
self.fuzzy_weighted = FuzzyComparator(method="weighted_ratio")
self.fuzzy_weighted = FuzzyComparator(method="ratio")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This now builds the same comparator as self.fuzzy_ratio on line 24, but the tests still treat it as its own method: test_mix_and_match collects it as weighted_score (152 and 163), and 127 and 180 assert on it. Could you drop this line, use self.fuzzy_ratio at 127 and 180, and remove weighted_score at 152 and 163? All 7 tests in the file still pass with that change.

@pcbeingused33

Copy link
Copy Markdown
Contributor Author

Dropped fuzzy_weighted. The product-description and multilingual assertions now call fuzzy_ratio, and test_mix_and_match no longer keeps a second ratio score. The seven tests in this file pass.

This comment was drafted with AI assistance.

@pcbeingused33

Copy link
Copy Markdown
Contributor Author

Hi, this was approved a few days ago. Is anything else needed before it can be merged? Happy to rebase if that helps. Thanks!

@sromoam sromoam added the anytime Non-breaking improvement off the release critical path: merge whenever it's ready label Dec 4, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

anytime Non-breaking improvement off the release critical path: merge whenever it's ready

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants