Repository navigation
fix: warn when NormalizedComparator is used on mappings - #331
Conversation
Security Scan ResultsASH Security Scan Report
Scan Metadata
SummaryScanner ResultsThe table below shows findings by scanner, with status based on severity thresholds and dependencies:
Top 2 HotspotsFiles with the highest number of security findings:
Detailed FindingsShow 4 actionable findingsFinding 1: SECRET-HEX-HIGH-ENTROPY-STRING
Description: Code Snippet: Finding 2: B108
Description: Code Snippet: Finding 3: B307
Description: Code Snippet: Finding 4: B307
Description: Code Snippet: Report generated by Automated Security Helper (ASH) at 2026-09-10T16:12:03+00:00 |
sromoam
left a comment
There was a problem hiding this comment.
Thanks for this — the diagnosis is right and the fix is the right shape. I verified the defect and the reasoning independently on dev at 6fbb425:
str({"k":"v","n":1}) normalizes to kvn1
str({"n":1,"k":"v"}) normalizes to n1kv
I also checked whether the alternative was better, and it is not: copying ExactComparator's canonicalization would be wrong here, because with ignore_punctuation=True the canonical JSON for {"a": "bc"} and {"ab": "c"} both collapse to abc. So canonicalizing would manufacture false matches. The denylist is the correct call, and it is worth writing that reasoning down (see below) because it is the load-bearing justification for the whole PR.
Requesting changes for two things. The rest are follow-ups and I would not hold the PR for them.
1. Blocking: no CHANGELOG entry for a silent score change
This turns a passing field into a false discovery. Measured, Optional[Dict[str, Any]] = ComparableField(comparator=NormalizedComparator()), both sides {"k": "v", "n": 1}:
dev@6fbb425 |
this branch | |
|---|---|---|
| same key order | 1.0 | 0.0 |
| reordered | 0.0 | 0.0 |
Same key order is the common case, since both sides usually come out of the same JSON loader. So anyone who set NormalizedComparator on a dict field loses every true positive on it, with no release note. The [Unreleased] block already documents much smaller movements than this one ("Scores move too, not just verdicts", "Scores move for list-of-mapping fields").
2. Blocking: two [Unreleased] enumerations become false
Both are in the block this PR ships under, so they would go out as release notes contradicted by their own release:
CHANGELOG.md:371— "...are refused, both on measured evidence." Three are refused now.CHANGELOG.md:424— "LevenshteinComparatorandFuzzyComparatorstay excluded" enumerates the set as exactly two.
:424 is worth fixing thoughtfully rather than mechanically. The sentence just before it establishes that ExactComparator was fixed by canonicalizing instead of being excluded, so a reader will immediately ask why NormalizedComparator was not given the same treatment. The punctuation-collision answer above is the reason, and it is currently written down nowhere.
Follow-ups, not blockers
comparison_dispatcher.py:232 is now contradicted by this PR's own test. The comment says the branch is "Reachable via Any or a multi-arm union, where no annotation declared the field a mapping" — but test_normalized_mapping.py reaches it from Optional[Dict[str, Any]], which is neither, and where an annotation did declare the field a mapping; the explicit comparator= merely suppressed the ANLS* substitution. It is the comment someone debugging this exact path reads first, and you updated both comments in configuration_helper.py, so this one is just a miss.
Nice touch on the monkeypatch.setattr(deprecation, "_warned", set()) in the test — without it the parametrised cases would have shadowed each other's warning through warn_once's process-lifetime memo.
| # comparator written outside this repo, since it could not know to opt in. | ||
| _COMPARATORS_THAT_CANNOT_SCORE_MAPPINGS = frozenset( | ||
| {"LevenshteinComparator", "FuzzyComparator"} | ||
| {"LevenshteinComparator", "FuzzyComparator", "NormalizedComparator"} |
There was a problem hiding this comment.
Verified gap, and I would call this a real defect rather than a nit: matching on __class__.__name__ misses a subclass of a comparator already known to be wrong on mappings.
class MyNorm(NormalizedComparator):
passOn a Dict[str, Any] field, measured on this branch:
MyNorm, same key order -> 1.0 and NO warning
MyNorm, reordered -> 0.0 and NO warning
That is exactly the defect the guard exists to catch — MyNorm inherits _normalize unchanged — and it passes through silently.
The rationale in the comment above ("by class name so an out-of-tree comparator is never caught by it") is about not catching unrelated comparators, which is right. It does not cover subclassing one of these three. Walking the MRO for in-tree base classes would close it while keeping that property, since an out-of-tree comparator that does not inherit from these is still never caught.
If you would rather not widen the check in this PR, noting the gap explicitly in the comment would be enough for me — the thing I would not want is for the comment to read as though the guard is complete.
| key reordering (0.667), so its ordering is | ||
| not defensible as a metric | ||
| NormalizedComparator flattens keys and values in insertion order, | ||
| so identical content can score 0.0 |
There was a problem hiding this comment.
One consequence worth deciding on deliberately: keying on the class name cannot see instance options, so a configuration that is provably safe gets refused.
NormalizedComparator(case_sensitive=True, ignore_whitespace=False, ignore_punctuation=False) performs no transforms at all, and is byte-identical to ExactComparator() on scalars. Measured on a Dict[str, Any] field:
NormalizedComparator(all transforms off) dev 1.0 -> this branch 0.0 + "scores scalars" warning
ExactComparator() dev 1.0 -> this branch 1.0 (canonicalized)
So a user who chose the explicit all-off spelling for auditability now gets a false discovery, where the semantically identical comparator gets a true positive.
The collision hazard only exists when a transform is actually active, so a conditional guard — refuse when ignore_punctuation or ignore_whitespace is on, canonicalize otherwise — would resolve it. That is more than this PR needs to take on; a sentence here recording that the refusal is deliberately unconditional would do.
|
Thanks for the detailed review. Added the score-change note and corrected both changelog lists, including the canonicalization collision example. I also corrected the dispatcher comment and documented the subclass gap and unconditional refusal policy, without widening the runtime check. Updated against current dev while preserving its dispatcher changes. The revised branch passes 323 focused/related tests and the full offline Linux suite (2,724 passed, 12 skipped). The six native Windows SIGALRM failures reproduce on unchanged dev; the verification section now includes that comparison. Removing the denylist entry still makes all four regression cases fail as expected. The update is pushed and ready for another look. |
sromoam
left a comment
There was a problem hiding this comment.
Approving
Both threads addressed the way I said would suffice: the gaps are now named in the code rather than papered over. Re-measured everything on cd805cb against this PR's own base (6580ecb), not read off the diff.
| case | base 6580ecb |
cd805cb |
|---|---|---|
Dict + NormalizedComparator, identical, same key order |
1.0, silent |
0.0 + warning |
| identical, keys reordered | 0.0, silent |
0.0 + warning |
| one value changed | 0.0, silent |
0.0 + warning |
all transforms off (case_sensitive=True, no whitespace/punctuation) |
1.0, silent |
0.0 + warning |
class MyNorm(NormalizedComparator), same order |
1.0, silent |
1.0, silent (documented gap) |
The first row is #315's exact symptom and it is gone. Suite: 2724 passed, 12 skipped.
The CHANGELOG is accurate, which I checked rather than assumed
Every measured number in the entry reproduces:
- "previously scored
1.0; it now scores0.0" for identical dicts: confirmed, row 1. - "Reordering the prediction's keys previously scored
0.0and still does, but now warns": confirmed, row 2. That precision matters, since the naive reading of this fix is that reordering is what changed. - "The refusal is unconditional, including when case, whitespace and punctuation options disable those transforms": confirmed, row 4.
- The collision argument in the amended #300/#223 entries, verified directly against
_normalize:
{"a": "bc"} canonical={"a": "bc"} normalized='abc'
{"ab": "c"} canonical={"ab": "c"} normalized='abc'
So canonicalizing before normalizing really would manufacture a 1.0 between two different mappings. Good call recording why the tempting fix is worse, and good call going back to amend the older entries so they do not now read as a complete list of refused comparators.
Two things I want to credit specifically
The stale comment in comparison_dispatcher.py. The old text said this path was reachable only "via Any or a multi-arm union, where no annotation declared the field a mapping". That was wrong after this change, since an explicit comparator on an Optional[Dict] reaches it too. Fixing a comment nobody asked about, in the one place that would have misled the next reader, is the part of this PR I would most want other contributors to copy.
The test resets _warned. monkeypatch.setattr(deprecation, "_warned", set()) is what makes the four parametrized cases independent. Without it, warn_once memoises for the process and three of the four assertions become vacuous depending on test order. That is a subtle trap and the test does not fall into it.
Scope check against #315
The issue asked for one frozenset entry plus a test that the warning fires and the field still scores rather than raising. That is what landed, plus the comment correction. NormalizedComparator itself is untouched, and a dict field with no explicit comparator still gets ANLSStarComparator, so nothing changes for anyone who did not name this comparator deliberately.
The two documented gaps, for the record
Neither blocks. Both are now findable by the next person, which is what I was actually asking for:
- A differently-named subclass still slips the denylist and still misscores silently. Named at
configuration_helper.py:31-32. - An all-transforms-off instance is refused despite being provably safe. Named at
configuration_helper.py:196-198.
If either bites someone post-1.0, walking the MRO closes the first and an option-aware guard closes the second. Not worth widening this PR for.
Issue #, if available:
Fixes #315.
Description of changes:
Add
NormalizedComparatorto the existing mapping denylist. Explicitly using it on a dictionary emits the existing warning and returns the existing rejected-mapping score instead of silently comparing flattened text. Scalar normalization and default structural mapping behavior are unchanged.The regression covers
compareandcompare_with, each with identical and reordered dictionary keys. It checks that evaluation warns and completes with a score of0.0.The changelog records the identical-mapping score change from
1.0to0.0, corrects both comparator lists, and explains why canonical JSON plus punctuation removal can manufacture matches. Comments also document the exact-class-name/subclass limitation, the unconditional instance-option policy, and the explicit-comparator route forOptional[Dict]. These review revisions do not expand runtime behavior.Verification
Updated against
devat6580ecb; final revisioncd805cb, Python 3.13.15, frozen dependencies:python -m pytest tests/comparators/test_normalized_mapping.py -q -o addopts= --tb=shortproduced four expected missing-warning failures before the fix. All four pass with it. Repeated the process-local negative control on this integrated revision: removing only the denylist entry again produces four expected missing-warning failures.python -m coverage run -m pytest tests/ -q -o addopts= --tb=short -ra— 2,724 passed, 12 skipped, 201 warnings; production-source coverage 85%.python -m pytest tests/ -q -o addopts= --tb=short -ra— 2,718 passed, 6 failed, 12 skipped. The identical command on unchangeddev@6580ecbgives 2,714 passed, the same 6 failed, 12 skipped. All six failures are the existing unavailablesignal.SIGALRMtimeout wrappers; all pass in Linux. No tests or timeouts were disabled.The 12 skips cover missing optional BERT/Strands extras and two existing unimplemented tests. Extra-enabled paths and other Python versions were not run locally; the hosted CI matrix must validate this updated head.
AI assistance was used for implementation and verification.
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.