Description
Describe your environment
OS: macOS Sequoia 15.4.1 (24E263)
Python version: 3.12.8
SDK version: 1.33.1
API version: 1.33.1
What happened?
Attributes for a datapoint are mutable after the datapoint has been recorded.
I discovered this using counters, I assume it affects all instruments, though.
If a reference to the mapping of the attributes passed into counter.add
is kept, the datapoints attributes created by calling add can be changed.
Steps to Reproduce
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import (
ConsoleMetricExporter,
PeriodicExportingMetricReader,
)
reader = PeriodicExportingMetricReader(ConsoleMetricExporter())
provider = MeterProvider(metric_readers=[reader])
meter = provider.get_meter("my-meter")
counter = meter.create_counter("my_counter")
# create a reference to the attributes
attributes = {"att": "value"}
counter.add(1, attributes)
# adjust the attributes after the first increment
attributes["att"] = "value2"
counter.add(1, attributes)
provider.force_flush()
provider.shutdown()
Expected Result
counter.add
creates an immutable copy of the attributes used in recording the metrics.
expected datapoints, the attributes are different for each datapoint:
"data_points": [
{
"attributes": {
"att": "value"
},
...
"value": 1,
...
},
{
"attributes": {
"att": "value2"
},
...
"value": 1,
...
}
]
Actual Result
counter.add
references the attribute object passed in without recording its value at the time of incrementation.
resulting in these datapoints, the attribute values are the same for each datapoint:
"data_points": [
{
"attributes": {
"att": "value2"
},
...
"value": 1,
...
},
{
"attributes": {
"att": "value2"
},
...
"value": 1,
...
}
]
Additional context
Downstream clients can fix this by passing in copies of their objects as a workaround. However, it was not obvious to me what was happening. My previous experience using Prometheus libraries suggests that holding a reference to the attributes object is ok.
It's also likely that I have misunderstood or misconfigured something. Please, feel free to point me in the correct direction if that is the case.
Please let me know if you agree if this is something that needs fixing and I'll see if I can submit a pull request.
Would you like to implement a fix?
Yes