Bug: DatadogProvider accepts non-finite (NaN, Infinity) metric values
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
- Initialize
DatadogMetrics(provider=DatadogProvider(flush_to_log=True)). - Add a metric with
value=float("nan")orvalue=float("inf"). - Call
flush_metrics(). - 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
- [x] This request meets Powertools for AWS Lambda (Python) Tenets.