Bug: Metrics keeps dimensions and metadata from an invocation that added no metrics

Open Beginner friendly
#8,911 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

@hyeonsang010716 is already working on this.

Since Nov 26, 2026.

  • #8912 by @hyeonsang010716 — open

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
79/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
aws, python

Research direction

Start with AmazonCloudWatchEMFProvider.flush_metrics() and the existing clear_metrics() behavior; the issue does not give file paths or test names. Check how flushing behaves when no metrics are emitted, validation raises, or metrics are disabled, then add or update coverage for those cases. Done when each flush clears invocation data and restores default dimensions, including when it warns or raises.

Written by the indexing model from the issue text.

Description

Expected Behaviour

Each invocation only emits the dimensions, dimension sets and metadata it added, plus the default dimensions. The docs for flush_metrics() say it will "serialize, print metrics available to standard output, and clear in-memory metrics data".

Current Behaviour

AmazonCloudWatchEMFProvider.flush_metrics() only calls clear_metrics() after it prints an EMF blob. Nothing is cleared when the flush emits nothing:

  1. The invocation added dimensions or metadata but no metrics, for example a handler that returns early. log_metrics warns No application metrics to publish and keeps everything in memory.
  2. raise_on_empty_metrics=True raises SchemaValidationError before the clear.
  3. POWERTOOLS_METRICS_DISABLED is set. Metric values keep piling up across invocations, and every invocation that sets the same dimension again warns Dimension '...' has already been added.

In cases 1 and 2 the next invocation on the same warm container emits the previous invocation's dimensions, dimension sets and metadata, so its datapoints land in the wrong CloudWatch series.

This is separate from #8902, which is about the custom timestamp.

Code snippet
import warnings

from aws_lambda_powertools import Metrics
from aws_lambda_powertools.metrics import MetricUnit

warnings.simplefilter("ignore")
metrics = Metrics(namespace="Orders", service="orders")


@metrics.log_metrics
def lambda_handler(event, context):
    if event.get("coupon"):
        metrics.add_dimension(name="coupon", value=event["coupon"])
        metrics.add_metadata(key="coupon_owner", value="user-123")
    if not event.get("items"):
        return  # nothing to record
    metrics.add_metric(name="OrdersPlaced", unit=MetricUnit.Count, value=1)


lambda_handler({"coupon": "BLACKFRIDAY"}, None)  # adds no metric
lambda_handler({"items": [1]}, None)  # no coupon

Output of the second invocation:

{"_aws":{"Timestamp":1795652054040,"CloudWatchMetrics":[{"Namespace":"Orders","Dimensions":[["coupon","service"]],"Metrics":[{"Name":"OrdersPlaced","Unit":"Count"}]}]},"coupon":"BLACKFRIDAY","service":"orders","coupon_owner":"user-123","OrdersPlaced":[1.0]}

Expected "Dimensions":[["service"]], with no coupon and no coupon_owner.

Possible Solution

Call clear_metrics() in a finally block in flush_metrics(), so every flush clears the in-memory data whether it printed, warned or raised. clear_metrics() already restores the default dimensions.

Steps to Reproduce
  1. Decorate a handler with @metrics.log_metrics.
  2. Invoke it once so it adds a dimension or metadata and returns without adding a metric.
  3. Invoke it again so it adds a metric without that dimension.
  4. The second EMF blob contains the dimension and metadata from step 2.
Did you run the reproduction yourself?

Yes, I ran it and saw the failure

Powertools for AWS Lambda (Python) version

3.41.0

AWS Lambda function runtime

3.14

Packaging format used

PyPi

Debugging logs

Dominant language
Python
Stars
3.3k
Forks
511
Avg merge
2d 23h
Merged PRs (30d)
50

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from aws-powertools/powertools-lambda-python

All issues in aws-powertools/powertools-lambda-python

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.