Skip to content

sdk/metrics: copy attributes dict to prevent post-recording mutation#5106

Open
tejasae-afk wants to merge 1 commit intoopen-telemetry:mainfrom
tejasae-afk:fix/metrics-attributes-copy
Open

sdk/metrics: copy attributes dict to prevent post-recording mutation#5106
tejasae-afk wants to merge 1 commit intoopen-telemetry:mainfrom
tejasae-afk:fix/metrics-attributes-copy

Conversation

@tejasae-afk
Copy link
Copy Markdown

When a caller retains a reference to the attributes dict passed to counter.add() (or any instrument's add/record call) and mutates it after the call, the mutation silently corrupts the attributes stored on the aggregation and therefore on exported data points.

The root cause is in _ViewInstrumentMatch.consume_measurement: when no attribute key filter is active, the code assigned the measurement's attributes dict directly:

# before
attributes = measurement.attributes

That dict is then passed to _create_aggregation, which stores it as self._attributes in the _Aggregation base class. Any subsequent mutation of the caller's dict changes what gets exported.

The fix is a one-line copy:

# after
attributes = dict(measurement.attributes)

A shallow copy is enough for all attribute value types (str, bool, int, float, and their sequence variants) because those values are themselves immutable once stored.

The filtered path (when _view._attribute_keys is not None) already builds a fresh dict via comprehension, so it is unaffected.

A regression test is included that records a measurement, mutates the original dict, and verifies the exported data point still carries the original attributes.

Closes #4610.

you know the codebase far better than I do, happy to adjust anything here.

…utation

When a caller retains a reference to the attributes dict passed to
counter.add() (or any instrument record/add call), mutating that dict
after the call would silently corrupt the attributes stored on the
aggregation and subsequently on exported data points.

The fix copies the dict at the point where it is first stored as the
canonical attributes for a new aggregation bucket, so downstream
mutations by the caller have no effect.

Fixes open-telemetry#4610
@linux-foundation-easycla
Copy link
Copy Markdown

CLA Not Signed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

Counter measurement attributes aren't immutable

1 participant