Bug: Metrics keeps dimensions and metadata from an invocation that added no metrics
Los mantenedores suelen responder en 1 día
@hyeonsang010716 ya está trabajando en esto.
Desde el 26/11/2026.
- #8912 de @hyeonsang010716 — abierto
Evaluación
- Dificultad
- 2/5
- Tiempo estimado
- 1-3 horas
- Aptitud para principiantes
- 79/100
- Tipo de issue
- Error
- Claridad
- Bien especificado
- Estado de actividad
- Activo
- Stack tecnológico
- aws, python
- Área
- backend, observability
Línea de trabajo
Empieza por AmazonCloudWatchEMFProvider.flush_metrics() y el comportamiento actual de clear_metrics(); el issue no proporciona rutas de archivos ni nombres de pruebas. Comprueba cómo se comporta el vaciado cuando no se emiten métricas, la validación genera una excepción o las métricas están desactivadas, y añade o actualiza la cobertura para esos casos. El trabajo está terminado cuando cada vaciado borra los datos de la invocación y restaura las dimensiones predeterminadas, incluso cuando se emite una advertencia o se genera una excepción.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
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:
- The invocation added dimensions or metadata but no metrics, for example a handler that returns early.
log_metricswarnsNo application metrics to publishand keeps everything in memory. raise_on_empty_metrics=TrueraisesSchemaValidationErrorbefore the clear.POWERTOOLS_METRICS_DISABLEDis set. Metric values keep piling up across invocations, and every invocation that sets the same dimension again warnsDimension '...' 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
- Decorate a handler with
@metrics.log_metrics. - Invoke it once so it adds a dimension or metadata and returns without adding a metric.
- Invoke it again so it adds a metric without that dimension.
- 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
- Lenguaje dominante
- Python
- Estrellas
- 3.3k
- Forks
- 511
- Merge medio
- 2 d 23 h
- PR fusionados (30 d)
- 50
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de aws-powertools/powertools-lambda-python
-
Bug: CaseInsensitiveDict (event.headers) returns True for both == and != against the same mappingAbiertobug triage
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
aws-powertools/powertools-lambda-python#8948 ·
Los mantenedores suelen responder en 1 día
-
Docs: child Logger without a parent uses the root log level since #8842Posiblemente ocupada @rdxrahul12 la tomó hoy. Abiertodocumentation triage
Dificultad 1/5 1-3 horas Aptitud para principiantes 85/100
aws-powertools/powertools-lambda-python#8935 · 3 comentarios ·
Los mantenedores suelen responder en 1 día
-
Bug: Set-Cookie values passed as a header are comma-joined into one invalid header on HTTP API and Function URL responsesPosiblemente ocupada @saquibjawedbit la tomó hace 4 días. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 85/100
aws-powertools/powertools-lambda-python#8921 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
-
Bug: validate() raises raw jmespath ParseError instead of InvalidEnvelopeExpressionError for most malformed envelopesPosiblemente ocupada @0x5t4l1n la tomó hoy. Abiertobug triage
Dificultad 2/5 1-3 horas Aptitud para principiantes 88/100
aws-powertools/powertools-lambda-python#8918 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
-
Bug: SQSRecord.decoded_nested_sns_event raises KeyError on SNS messages delivered to SQSPosiblemente ocupada @hyeonsang010716 la tomó hace 7 días. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 79/100
aws-powertools/powertools-lambda-python#8913 ·
Los mantenedores suelen responder en 1 día
Todos los issues de aws-powertools/powertools-lambda-python
Issues similares
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
litestar-org/sqlspec#946 ·
Los mantenedores suelen responder en 1 día
-
area:cli area:docs Platform vdr
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
NVIDIA-NeMo/Gym#7192 ·
Los mantenedores suelen responder en 2 días
-
SofyaBotAbierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 66/100
ai-robots-txt/ai.robots.txt#324 ·
-
[Resource]: DashbarAbiertoresource-submission validation-passed
Dificultad 1/5 Menos de una hora Aptitud para principiantes 78/100
hesreallyhim/awesome-claude-code#3821 · 1 comentario ·
-
bug good first issue help wanted level 1 wocs
Dificultad 2/5 1-3 horas Aptitud para principiantes 92/100
GianlucaBave/murmury#169 ·
Los mantenedores suelen responder en 1 día