Skip to content

fix: treat a float NaN as absent, the same as None (#367) - #381

Merged
sromoam merged 1 commit into
awslabs:devfrom
harrycav:fix/367-nan-as-absent
Oct 13, 2026
Merged

sromoam merged 1 commit into
awslabs:devfrom
harrycav:fix/367-nan-as-absent

Conversation

@harrycav

@harrycav harrycav commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Issue Reference

Fixes #367

Description of Changes

A float NaN is now treated as absent, the same as None. Two identical NaNs used to score 0.0 and count as a false discovery.

Changes Made

  • NullHelper.is_nan() added; is_effectively_null_for_primitives, its _maybe_absent guard, and FieldHelper.is_null_value all treat a float NaN as null.
  • BaseComparator.compare()'s shared None policy also treats a float NaN as missing, so list elements and direct comparator calls agree with the field path.
  • Docs (classification-logic.md) and a CHANGELOG Fixed entry.
GT vs pred Before After
NaN vs NaN 0.0, FD 1.0, TN
NaN vs None 0.0, FN 1.0, TN
NaN vs 5.0 0.0, FD 0.0, FA
5.0 vs NaN 0.0, FD 0.0, FN

Why These Changes Are Needed

NaN is how pandas and numpy spell a missing number, and it isn't valid JSON, so it's not a value an extractor is asked to produce. #367 names "absent" and "not a value" as the two readings. This PR takes "absent", which matches how stickler already treats "" and {}.

Testing

  • Unit tests added/updated: new test_nan_as_absent.py (9 of its 10 tests fail on dev; the 10th pins unchanged Decimal behaviour)
  • test_nan_does_not_crash flipped to test_nan_reads_as_absent; NaN added to the _maybe_absent superset test
  • Manual testing: compare_with, eval_for, direct comparator, List[StructuredModel]
  • All existing tests pass: 2779 passed, 12 skipped, 1 xfailed (macOS, against dev @ 1479c3d)

Reviewers

@sromoam

Checklist

  • Code follows the project's coding standards
  • Self-review of code completed
  • Documentation updated (if applicable)
  • CHANGELOG.md entry added under [Unreleased]
  • Tests added/updated for new functionality
  • All CI checks are passing
  • Ready for review

Additional Notes

  • This reverses a deliberate choice. The "NaN matches nothing" guard in Num542f724. That guard still stops the InvalidOperationcrash; a floatNaN`just no longer reaches it.
  • Confusion counts change for any field holding NaN (FD becomes TN/FA/FN),
  • Only a float NaN is absent (numpy floats included). A Decimal('NaN') still matches nothing.
  • The base.py change applies to every comparator, not just numeric.

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

Two identical NaNs scored 0.0 and counted as a false discovery, because
NaN equals nothing under IEEE 754. NaN is how pandas and numpy spell a
missing number, so read it as absent everywhere absence is decided:
NullHelper (and its _maybe_absent guard), FieldHelper.is_null_value, and
BaseComparator.compare's shared None policy.

NaN vs NaN or None is now TN/1.0, NaN vs a number FA or FN. A Decimal
NaN is unchanged and still matches nothing.
@harrycav
harrycav requested a review from sromoam as a code owner October 9, 2026 15:07
@digalaviz
digalaviz self-requested a review October 9, 2026 19:34
@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-10-09T23:15:35+00:00
  • Time since scan: 3 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-10-09T23:12:29+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 5755 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:1362-1368

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:1367-1369

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-10-09T23:15:36+00:00

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

What I verified:

  • Two isolated clones, baseline dev @ 1479c3d4 and this PR @ 6a259d80, each
    installed with uv sync --frozen (the CI command). Both import their own tree —
    worth stating because __version__ reads 1.0.0 on both, so it cannot tell them
    apart; I used hasattr(NullHelper, 'is_nan') as the discriminator instead.
  • Full suite green on both: baseline 2769 passed, 12 skipped, 1 xfailed, candidate
    2779 passed, 12 skipped, 1 xfailed. +10 passed, zero new failures, skip/xfail
    counts unchanged. CI is green on 6a259d80 across all seven checks too, which
    matches what I measured locally.
  • No dependency surface touched pyproject.toml, uv.lock and the requirements
    are untouched in the diff, uv lock --check passes, and both trees resolve the
    same 169 packages. So the two environments are directly comparable.
  • No security findings. Nothing added uses eval/exec/pickle/subprocess, no new
    imports beyond stdlib math, and is_nan is safe on every input type I threw at
    it (None, str, list, Decimal, numpy scalars, pydantic models) because the
    isinstance guard short-circuits.

One non-blocking note on null_helper.py, below. Nothing that should hold the merge.

Returns:
True if the value is a float (including ``numpy.float64``) NaN
"""
return isinstance(val, float) and math.isnan(val)

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.

Non-blocking, and you already documented this at L40 ("including numpy.float64"),
so this is a question about intent rather than a defect.

isinstance(val, float) catches a Python float and np.float64 (a float subclass),
but not np.float32, np.float16, or np.longdouble. Measured:

value baseline 1479c3d4 this PR 6a259d80
NumericComparator().compare(v, v), py-float / float64 NaN 0.0 1.0
same, np.float32 / np.float16 NaN 0.0 0.0

So the same missing value scores differently by dtype width, where the baseline was
uniformly 0.0.

Two things keep this low rather than blocking, and I want to be straight about both:

The normal path is fine. On a field annotated Optional[float], pydantic coerces
every numpy width to a Python float, so all four widths score 1.0 with a true
negative on your branch (all 0.0 with a false discovery on dev). A pandas float32
column bound to a typed float field is fully fixed. The split is only reachable via a
direct comparator call or a field annotated Any.

And the unfixed widths sit exactly at the old behaviour, so this is an incomplete fix
rather than a regression. Nothing got worse.

The part I think is worth acting on regardless: test_numpy_nan_is_absent exercises
np.float64 through a typed Optional[float] field, so pydantic coercion carries it
— the test would pass identically with no numpy handling at all. It doesn't currently
pin the numpy support it's named for. A case going through a direct comparator call or
an Any field would.

If you do want to widen it, concrete types read better here than an ABC:

return isinstance(val, (float, np.floating)) and math.isnan(val)

That needs an import numpy as np at the top — this module currently imports only
math and typing, which is why I'm not leaving it as a one-click suggestion.

I tried numbers.Real first and talked myself out of it: it admits int, bool and
Fraction, which can never be NaN, so a reader of a function named is_nan has to
work out why integers are in scope — and it still excludes Decimal('NaN'), since
Decimal isn't registered as numbers.Real. It looks more general than it is, which
is worse to maintain than your explicit float64-only scope. (Cost is not the reason:
I measured ~184ns vs ~38ns per call, which is nothing at field-per-case volume.)

Equally fine to declare float64-only the intended scope and just tighten the test. The
test gap is the part I'd act on; the predicate is your call.

Measured on two isolated clones, baseline dev @ 1479c3d4 and this PR @ 6a259d80,
each importing its own tree — __version__ is 1.0.0 on both, so I keyed off
hasattr(NullHelper, 'is_nan') instead.

@digalaviz digalaviz 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. Raised eight candidate findings adversarially; seven turned out to be pre-existing behaviour on dev, one stands as the non-blocking note above

@sromoam
sromoam merged commit 70e9afb into awslabs:dev Oct 13, 2026
7 checks passed
sromoam added a commit that referenced this pull request Oct 14, 2026
Resolve the conflicts with #381 (NaN as absent): both changes extend the
same null rules, so NullHelper.is_effectively_null_for_primitives and the
_maybe_absent guard now treat NaN and empty tuples/sets as absent, and the
null rule in classification-logic.md and the CHANGELOG keep both entries.
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.

An identical pair of nan float values scores 0.0 instead of 1.0

3 participants