Skip to content

fix: warn when NormalizedComparator is used on mappings - #331

Merged
sromoam merged 3 commits into
awslabs:devfrom
hugosmoreira:fix/315-normalized-mapping-guard
Sep 11, 2026
Merged

sromoam merged 3 commits into
awslabs:devfrom
hugosmoreira:fix/315-normalized-mapping-guard

Conversation

@hugosmoreira

@hugosmoreira hugosmoreira commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Issue #, if available:

Fixes #315.

Description of changes:

Add NormalizedComparator to 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 compare and compare_with, each with identical and reordered dictionary keys. It checks that evaluation warns and completes with a score of 0.0.

The changelog records the identical-mapping score change from 1.0 to 0.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 for Optional[Dict]. These review revisions do not expand runtime behavior.

Verification

Updated against dev at 6580ecb; final revision cd805cb, Python 3.13.15, frozen dependencies:

  • Original test-first command: python -m pytest tests/comparators/test_normalized_mapping.py -q -o addopts= --tb=short produced 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.
  • Focused/related and changelog-contract modules: 323 passed on native Windows.
  • Full offline Linux container suite: python -m coverage run -m pytest tests/ -q -o addopts= --tb=short -ra — 2,724 passed, 12 skipped, 201 warnings; production-source coverage 85%.
  • Full native Windows suite: python -m pytest tests/ -q -o addopts= --tb=short -ra — 2,718 passed, 6 failed, 12 skipped. The identical command on unchanged dev@6580ecb gives 2,714 passed, the same 6 failed, 12 skipped. All six failures are the existing unavailable signal.SIGALRM timeout wrappers; all pass in Linux. No tests or timeouts were disabled.
  • Scoped Ruff, final diff checks, offline wheel/source-distribution build and dependency compatibility checks passed. Repository-wide Ruff has the same 16 lint findings and 140 formatting candidates as unchanged upstream; no unrelated formatting changes are included.
  • Verified the maintainer's score/canonicalization examples and the documented subclass/instance-option limitations. AST comparison confirms upstream executable code is preserved except for the original denylist entry. Tested source, final checkout and packaged changed source were checked for identity.

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.

@github-actions

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-09-10T16:12:01+00:00
  • Time since scan: 2 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-09-10T16:09:17+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 3 0 0 5393 0 3 FAILED 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 1 0 0 0 0 1 SKIPPED 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 3 0 0 0 0 0 0 PASSED MEDIUM (global)
syft 0 0 0 0 0 0 0 MISSING MEDIUM (global)

Top 2 Hotspots

Files with the highest number of security findings:

Finding Count File Location
2 tests/comparators/test_anls_leaf_semantics.py
2 tests/structured_object_evaluator/test_rollup_node_semantics.py

Detailed Findings

Show 4 actionable findings

Finding 1: SECRET-HEX-HIGH-ENTROPY-STRING

  • Severity: HIGH
  • Scanner: detect-secrets
  • Rule ID: SECRET-HEX-HIGH-ENTROPY-STRING
  • Location: tests/comparators/test_anls_leaf_semantics.py:89

Description:
Secret of type 'Hex High Entropy String' detected in file 'tests/comparators/test_anls_leaf_semantics.py' at line 89

Code Snippet:

Secret of type Hex High Entropy String detected

Finding 2: B108

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B108
  • Location: tests/comparators/test_anls_leaf_semantics.py:210-212

Description:
Probable insecure usage of temp file/directory.

Code Snippet:

uuid.UUID(int=1),
            pathlib.Path("/tmp/x"),
            b"bytes",

Finding 3: B307

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B307
  • Location: tests/structured_object_evaluator/test_rollup_node_semantics.py:1343-1349

Description:
Use of possibly insecure function - consider using safer ast.literal_eval.

Code Snippet:

def published_label(node: dict, section: str, object_lists: set) -> str:
            counts_objects = eval(  # noqa: S307
                cond.group(1),
                {},
                {"data": node, "section": section, "OBJECT_LISTS": object_lists},
            )
            return eval(unit.group(1), {}, {"counts_objects": counts_objects})  # noqa: S307

Finding 4: B307

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B307
  • Location: tests/structured_object_evaluator/test_rollup_node_semantics.py:1348-1350

Description:
Use of possibly insecure function - consider using safer ast.literal_eval.

Code Snippet:

)
            return eval(unit.group(1), {}, {"counts_objects": counts_objects})  # noqa: S307

Report generated by Automated Security Helper (ASH) at 2026-09-10T16:12:03+00:00

@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 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 — "LevenshteinComparator and FuzzyComparator stay 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"}

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.

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

On 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

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.

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.

@hugosmoreira

Copy link
Copy Markdown
Contributor Author

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

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 scores 0.0" for identical dicts: confirmed, row 1.
  • "Reordering the prediction's keys previously scored 0.0 and 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:

  1. A differently-named subclass still slips the denylist and still misscores silently. Named at configuration_helper.py:31-32.
  2. 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.

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.

[BUG]: NormalizedComparator scores a dict by key order, silently, and is missing from the mapping denylist

2 participants