powertools-lambda-python icon indicating copy to clipboard operation
powertools-lambda-python copied to clipboard

Bug: DatadogProvider accepts non-finite (NaN, Infinity) metric values

Open dhaiirryyaa opened this issue 2 weeks ago • 0 comments

Expected Behaviour

DatadogProvider.add_metric should reject or skip non-finite values (NaN, Infinity, -Infinity) with a warning, matching the behavior implemented for CloudWatch EMF in #8796 and #8797, so that non-finite values do not corrupt metric serialization or flush invalid JSON.

Current Behaviour

In aws_lambda_powertools/metrics/provider/datadog/datadog.py, add_metric only checks isinstance(value, numbers.Real). Since float("nan"), float("inf"), and float("-inf") are instances of numbers.Real, they pass validation and are appended to self.metric_set.

When flush_to_log=True, print(json.dumps(metric)) outputs bare NaN / Infinity, which is invalid JSON per RFC 8259 and causes downstream log processors and JSON parsers to fail. When flushed through datadog_lambda, Datadog expects 32-bit finite floats.

Code snippet

import json
from aws_lambda_powertools.metrics.provider.datadog import DatadogMetrics, DatadogProvider

dd_provider = DatadogProvider(flush_to_log=True)
metrics = DatadogMetrics(provider=dd_provider)

metrics.add_metric(name="orders", value=1.0)
metrics.add_metric(name="avg_basket", value=float("nan"))
metrics.flush_metrics()
# Flushes: {"m":"avg_basket","v":NaN,"e":...,"t":[]} -> invalid JSON

Steps to Reproduce

  1. Initialize DatadogMetrics(provider=DatadogProvider(flush_to_log=True)).
  2. Add a metric with value=float("nan") or value=float("inf").
  3. Call flush_metrics().
  4. Observe invalid JSON emitted with bare NaN / Infinity.

Possible Solution

Add a check for math.isfinite(value) in DatadogProvider.add_metric:

if not math.isfinite(value):
    warnings.warn(
        f"The metric {name} has a non-finite value ({value}) and won't be added. "
        "Datadog only accepts finite numbers.",
        category=PowertoolsUserWarning,
        stacklevel=2,
    )
    return

Acknowledgment

dhaiirryyaa avatar Nov 16 '26 17:11 dhaiirryyaa