Datasets:
Download instances/observability-opentelemetry-python-5266/gold/candidate.patch from CrossSWE/CrossSWE-Bench: direct link, hf CLI and curl.
- Browser
- Download file 118 kB
-
https://huggingface.co/datasets/CrossSWE/CrossSWE-Bench/resolve/main/instances/observability-opentelemetry-python-5266/gold/candidate.patch
- Command line
-
hf download hf://datasets/CrossSWE/CrossSWE-Bench/instances/observability-opentelemetry-python-5266/gold/candidate.patch
-
curl -L -o candidate.patch https://huggingface.co/datasets/CrossSWE/CrossSWE-Bench/resolve/main/instances/observability-opentelemetry-python-5266/gold/candidate.patch
118 kB
| diff --git a/.changelog/5266.added b/.changelog/5266.added | |
| new file mode 100644 | |
| index 00000000..66f88e9f | |
| --- /dev/null | |
| +++ b/.changelog/5266.added | |
| @@ -0,0 +1 @@ | |
| +`opentelemetry-api`, `opentelemetry-sdk`: add support for extended attribute values everywhere. | |
| \ No newline at end of file | |
| diff --git a/.changelog/5266.changed b/.changelog/5266.changed | |
| new file mode 100644 | |
| index 00000000..dbb19eb7 | |
| --- /dev/null | |
| +++ b/.changelog/5266.changed | |
| +The public `opentelemetry.util.types.AttributeValue` type in package `opentelemetry-api` is being expanded to include `None`, heterogeneous sequences of primitive types (and nested sequences) as opposed to only homogeneous primitive sequences, and Mappings of strings to any primitive types or sequences/mappings (which themselves must only contain primitive types or sequences/mappings validated the same way). | |
| +If a `bytes` type is set as an attribute value in the SDK, it will no longer be utf-8 decoded to a string, instead it will be passed along as is in accordance with the OTEL spec, since `bytes` is a valid type in the OTLP proto. | |
| \ No newline at end of file | |
| diff --git a/docs/conf.py b/docs/conf.py | |
| index e0058937..20d53cd2 100644 | |
| --- a/docs/conf.py | |
| +++ b/docs/conf.py | |
| from django.conf import settings | |
| settings.configure() | |
| -# Provide AnyValue in opentelemetry.attributes module's namespace so the | |
| -# "AnyValue" forward reference in opentelemetry.util.types._ExtendedAttributes | |
| -# resolves when sphinx_autodoc_typehints calls typing.get_type_hints() on | |
| -# BoundedAttributes (whose __globals__ is the attributes module). Docs-only. | |
| -import opentelemetry.attributes # noqa: E402 | |
| -from opentelemetry.util.types import AnyValue as _AnyValue # noqa: E402 | |
| +# Docs-only: resolves the "AnyValue" forward reference wherever | |
| +# get_type_hints() evaluates it. AnyValue is a recursive alias, so | |
| +# modules that import it only under TYPE_CHECKING hit a NameError. | |
| +# TODO: https://github.com/open-telemetry/opentelemetry-python/issues/5304 | |
| +# this can be removed by importing AnyValue at runtime in the | |
| +# modules that annotate with it | |
| +import builtins # noqa: E402 | |
| -opentelemetry.attributes.AnyValue = _AnyValue | |
| +from opentelemetry.util.types import AnyValue # noqa: E402 | |
| + | |
| +builtins.AnyValue = AnyValue | |
| source_dirs = [ | |
| nitpick_ignore = [ | |
| "py:class", | |
| "AnyValue", | |
| ), | |
| - ( | |
| - "py:class", | |
| - "_ExtendedAttributes", | |
| - ), | |
| ("py:class", "Token"), | |
| # ``from os import PathLike`` renders as the bare name ``PathLike`` in the | |
| # file exporter type hints, which sphinx cannot resolve to os.PathLike. | |
| diff --git a/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/__init__.py b/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/__init__.py | |
| index f293ae99..017c8aa3 100644 | |
| --- a/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/__init__.py | |
| +++ b/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/__init__.py | |
| from opentelemetry.proto_json.resource.v1.resource import ( | |
| ) | |
| from opentelemetry.sdk.resources import Resource | |
| from opentelemetry.sdk.util.instrumentation import InstrumentationScope | |
| -from opentelemetry.util.types import _ExtendedAttributes | |
| +from opentelemetry.util.types import Attributes | |
| _logger = logging.getLogger(__name__) | |
| def _encode_trace_id(trace_id: int) -> bytes: | |
| def _encode_attributes( | |
| - attributes: _ExtendedAttributes | None, | |
| + attributes: Attributes, | |
| ) -> list[JSONKeyValue]: | |
| if not attributes: | |
| return [] | |
| diff --git a/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/_log_encoder/__init__.py b/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/_log_encoder/__init__.py | |
| index 6b3ab356..1dee399d 100644 | |
| --- a/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/_log_encoder/__init__.py | |
| +++ b/exporter/opentelemetry-exporter-otlp-json-common/src/opentelemetry/exporter/otlp/json/common/_internal/_log_encoder/__init__.py | |
| def _encode_log(readable_log_record: ReadableLogRecord) -> JSONLogRecord: | |
| flags=int(readable_log_record.log_record.trace_flags), | |
| body=_encode_value(readable_log_record.log_record.body), | |
| severity_text=readable_log_record.log_record.severity_text, | |
| - attributes=_encode_attributes( | |
| - cast(Attributes, readable_log_record.log_record.attributes), | |
| - ), | |
| + attributes=_encode_attributes(cast(Attributes, readable_log_record.log_record.attributes)), | |
| dropped_attributes_count=readable_log_record.dropped_attributes, | |
| severity_number=getattr(readable_log_record.log_record.severity_number, "value", None), | |
| event_name=readable_log_record.log_record.event_name, | |
| diff --git a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_exporter_metrics.py b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_exporter_metrics.py | |
| index 720334c9..1524e1dc 100644 | |
| --- a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_exporter_metrics.py | |
| +++ b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_exporter_metrics.py | |
| if TYPE_CHECKING: | |
| from typing import Literal | |
| from urllib.parse import ParseResult as UrlParseResult | |
| - from opentelemetry.util.types import Attributes, AttributeValue | |
| + from opentelemetry.util.types import AnyValue, Attributes | |
| _component_counter = Counter() | |
| class ExporterMetrics: | |
| component_type_value = component_type.value if component_type else "unknown_otlp_exporter" | |
| count = _component_counter[component_type_value] | |
| _component_counter[component_type_value] = count + 1 | |
| - self._standard_attrs: dict[str, AttributeValue] = { | |
| + self._standard_attrs: dict[str, AnyValue] = { | |
| OTEL_COMPONENT_TYPE: component_type_value, | |
| OTEL_COMPONENT_NAME: f"{component_type_value}/{count}", | |
| } | |
| diff --git a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/__init__.py b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/__init__.py | |
| index a5541ff9..55895fc8 100644 | |
| --- a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/__init__.py | |
| +++ b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/__init__.py | |
| from opentelemetry.proto.resource.v1.resource_pb2 import ( | |
| ) | |
| from opentelemetry.sdk.trace import Resource | |
| from opentelemetry.sdk.util.instrumentation import InstrumentationScope | |
| -from opentelemetry.util.types import _ExtendedAttributes | |
| +from opentelemetry.util.types import Attributes | |
| _logger = logging.getLogger(__name__) | |
| def _encode_trace_id(trace_id: int) -> bytes: | |
| return trace_id.to_bytes(length=16, byteorder="big", signed=False) | |
| -def _encode_attributes( | |
| - attributes: _ExtendedAttributes | None, | |
| -) -> list[PB2KeyValue]: | |
| +def _encode_attributes(attributes: Attributes) -> list[PB2KeyValue]: | |
| if not attributes: | |
| return [] | |
| pb2_attributes = [] | |
| diff --git a/exporter/opentelemetry-exporter-otlp-proto-grpc/benchmarks/test_benchmark_trace_exporter.py b/exporter/opentelemetry-exporter-otlp-proto-grpc/benchmarks/test_benchmark_trace_exporter.py | |
| index db583f69..b8ae543c 100644 | |
| --- a/exporter/opentelemetry-exporter-otlp-proto-grpc/benchmarks/test_benchmark_trace_exporter.py | |
| +++ b/exporter/opentelemetry-exporter-otlp-proto-grpc/benchmarks/test_benchmark_trace_exporter.py | |
| class MockTraceServiceStub: | |
| @patch( | |
| - "opentelemetry.exporter.otlp.proto.grpc.trace_exporter.OTLPSpanExporter._stub", | |
| + "opentelemetry.exporter.otlp.proto.grpc.trace_exporter.TraceServiceStub", | |
| new=MockTraceServiceStub, | |
| ) | |
| def test_simple_span_processor(benchmark): | |
| def test_simple_span_processor(benchmark): | |
| @patch( | |
| - "opentelemetry.exporter.otlp.proto.grpc.trace_exporter.OTLPSpanExporter._stub", | |
| + "opentelemetry.exporter.otlp.proto.grpc.trace_exporter.TraceServiceStub", | |
| new=MockTraceServiceStub, | |
| ) | |
| def test_batch_span_processor(benchmark): | |
| diff --git a/exporter/opentelemetry-exporter-prometheus/src/opentelemetry/exporter/prometheus/__init__.py b/exporter/opentelemetry-exporter-prometheus/src/opentelemetry/exporter/prometheus/__init__.py | |
| index 5c129db8..80421fd7 100644 | |
| --- a/exporter/opentelemetry-exporter-prometheus/src/opentelemetry/exporter/prometheus/__init__.py | |
| +++ b/exporter/opentelemetry-exporter-prometheus/src/opentelemetry/exporter/prometheus/__init__.py | |
| from opentelemetry.sdk.util.instrumentation import InstrumentationScope | |
| from opentelemetry.semconv._incubating.attributes.otel_attributes import ( | |
| OtelComponentTypeValues, | |
| ) | |
| -from opentelemetry.util.types import Attributes, AttributeValue | |
| +from opentelemetry.util.types import AnyValue, Attributes | |
| _logger = getLogger(__name__) | |
| class _CustomCollector: | |
| def _translate_metric( | |
| self, | |
| metric: Metric, | |
| - scope_attrs: dict[str, AttributeValue], | |
| - resource_attrs: dict[str, AttributeValue], | |
| + scope_attrs: dict[str, AnyValue], | |
| + resource_attrs: dict[str, AnyValue], | |
| metric_family_id_metric_family: dict[str, PrometheusMetric], | |
| ) -> None: | |
| metric_name = self._resolve_metric_name(metric.name) | |
| class _CustomCollector: | |
| else: | |
| _logger.warning("Unsupported metric data. %s", type(metric.data)) | |
| - def _build_scope_attrs(self, scope: InstrumentationScope) -> dict[str, AttributeValue]: | |
| + def _build_scope_attrs(self, scope: InstrumentationScope) -> dict[str, AnyValue]: | |
| if not self._scope_info_enabled: | |
| return {} | |
| - attrs: dict[str, AttributeValue] = {} | |
| + attrs: dict[str, AnyValue] = {} | |
| if scope.attributes: | |
| for key, value in scope.attributes.items(): | |
| attrs[_OTEL_SCOPE_ATTR_PREFIX + key] = value | |
| class _CustomCollector: | |
| attrs[_OTEL_SCOPE_SCHEMA_URL_LABEL] = scope.schema_url or "" | |
| return attrs | |
| - def _build_resource_attrs(self, resource: Resource) -> dict[str, AttributeValue]: | |
| + def _build_resource_attrs(self, resource: Resource) -> dict[str, AnyValue]: | |
| if not self._resource_attribute_filter: | |
| return {} | |
| return {key: value for key, value in resource.attributes.items() if self._resource_attribute_filter(key)} | |
| class _CustomCollector: | |
| def _collect_data_points( | |
| self, | |
| metric_data: DataT, | |
| - scope_attrs: dict[str, AttributeValue], | |
| - resource_attrs: dict[str, AttributeValue], | |
| + scope_attrs: dict[str, AnyValue], | |
| + resource_attrs: dict[str, AnyValue], | |
| ) -> tuple[list[str], list[list[str]], list[float | dict[str, Any]]]: | |
| keys: set[str] = set() | |
| rows: list[dict[str, str]] = [] | |
| diff --git a/opentelemetry-api/src/opentelemetry/_logs/_internal/__init__.py b/opentelemetry-api/src/opentelemetry/_logs/_internal/__init__.py | |
| index cc90523c..207147bf 100644 | |
| --- a/opentelemetry-api/src/opentelemetry/_logs/_internal/__init__.py | |
| +++ b/opentelemetry-api/src/opentelemetry/_logs/_internal/__init__.py | |
| from opentelemetry.trace import get_current_span | |
| from opentelemetry.trace.span import TraceFlags | |
| from opentelemetry.util._once import Once | |
| from opentelemetry.util._providers import _load_provider | |
| -from opentelemetry.util.types import AnyValue, _ExtendedAttributes | |
| +from opentelemetry.util.types import AnyValue, Attributes | |
| _logger = getLogger(__name__) | |
| class LogRecord(ABC): | |
| severity_text: str | None = None, | |
| severity_number: SeverityNumber | None = None, | |
| body: AnyValue = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| event_name: str | None = None, | |
| exception: BaseException | None = None, | |
| ) -> None: ... | |
| class LogRecord(ABC): | |
| severity_text: str | None = None, | |
| severity_number: SeverityNumber | None = None, | |
| body: AnyValue = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> None: ... | |
| def __init__( | |
| class LogRecord(ABC): | |
| severity_text: str | None = None, | |
| severity_number: SeverityNumber | None = None, | |
| body: AnyValue = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| event_name: str | None = None, | |
| exception: BaseException | None = None, | |
| ) -> None: | |
| class Logger(ABC): | |
| name: str, | |
| version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> None: | |
| super().__init__() | |
| self._name = name | |
| class Logger(ABC): | |
| severity_number: SeverityNumber | None = None, | |
| severity_text: str | None = None, | |
| body: AnyValue | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| event_name: str | None = None, | |
| exception: BaseException | None = None, | |
| ) -> None: ... | |
| class Logger(ABC): | |
| severity_number: SeverityNumber | None = None, | |
| severity_text: str | None = None, | |
| body: AnyValue | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| event_name: str | None = None, | |
| exception: BaseException | None = None, | |
| ) -> None: | |
| class NoOpLogger(Logger): | |
| severity_number: SeverityNumber | None = None, | |
| severity_text: str | None = None, | |
| body: AnyValue | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| event_name: str | None = None, | |
| exception: BaseException | None = None, | |
| ) -> None: ... | |
| class NoOpLogger(Logger): | |
| severity_number: SeverityNumber | None = None, | |
| severity_text: str | None = None, | |
| body: AnyValue | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| event_name: str | None = None, | |
| exception: BaseException | None = None, | |
| ) -> None: | |
| class ProxyLogger(Logger): | |
| name: str, | |
| version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| ): | |
| self._name = name | |
| self._version = version | |
| class ProxyLogger(Logger): | |
| severity_number: SeverityNumber | None = None, | |
| severity_text: str | None = None, | |
| body: AnyValue | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| event_name: str | None = None, | |
| exception: BaseException | None = None, | |
| ) -> None: ... | |
| class ProxyLogger(Logger): | |
| severity_number: SeverityNumber | None = None, | |
| severity_text: str | None = None, | |
| body: AnyValue | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| event_name: str | None = None, | |
| exception: BaseException | None = None, | |
| ) -> None: | |
| class LoggerProvider(ABC): | |
| name: str, | |
| version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> Logger: | |
| """Returns a `Logger` for use by the given instrumentation library. | |
| class NoOpLoggerProvider(LoggerProvider): | |
| name: str, | |
| version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> Logger: | |
| """Returns a NoOpLogger.""" | |
| return NoOpLogger(name, version=version, schema_url=schema_url, attributes=attributes) | |
| class ProxyLoggerProvider(LoggerProvider): | |
| name: str, | |
| version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> Logger: | |
| if _LOGGER_PROVIDER: | |
| return _LOGGER_PROVIDER.get_logger( | |
| def get_logger( | |
| instrumenting_library_version: str = "", | |
| logger_provider: LoggerProvider | None = None, | |
| schema_url: str | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> Logger: | |
| """Returns a `Logger` for use within a python process. | |
| diff --git a/opentelemetry-api/src/opentelemetry/attributes/__init__.py b/opentelemetry-api/src/opentelemetry/attributes/__init__.py | |
| index c6715321..2ba2d393 100644 | |
| --- a/opentelemetry-api/src/opentelemetry/attributes/__init__.py | |
| +++ b/opentelemetry-api/src/opentelemetry/attributes/__init__.py | |
| # Copyright The OpenTelemetry Authors | |
| # SPDX-License-Identifier: Apache-2.0 | |
| +# pyright: reportUnnecessaryIsInstance=false | |
| + | |
| import copy | |
| import logging | |
| import threading | |
| -from collections import OrderedDict | |
| from collections.abc import Mapping, MutableMapping, Sequence | |
| +from types import NoneType | |
| +from typing import TYPE_CHECKING, Any, overload | |
| + | |
| +from typing_extensions import assert_never, deprecated | |
| from opentelemetry.util import types | |
| -# bytes are accepted as a user supplied value for attributes but | |
| -# decoded to strings internally. | |
| -_VALID_ATTR_VALUE_TYPES = (bool, str, bytes, int, float) | |
| -# AnyValue possible values | |
| -_VALID_ANY_VALUE_TYPES = ( | |
| - type(None), | |
| - bool, | |
| - bytes, | |
| - int, | |
| - float, | |
| - str, | |
| - Sequence, | |
| - Mapping, | |
| -) | |
| - | |
| - | |
| -# TODO: Remove this workaround and revert to the simpler implementation | |
| -# once Python 3.9 support is dropped (planned around May 2026). | |
| -# This exists only to avoid issues caused by deprecated behavior in 3.9. | |
| -def _type_name(t): | |
| - return getattr(t, "__name__", getattr(t, "_name", repr(t))) | |
| +_logger = logging.getLogger(__name__) | |
| -_logger = logging.getLogger(__name__) | |
| +# Calling str(x) will use an object's `__str__` method if it exists, otherwise it will use it's `__repr__` method. | |
| +# If neither is defined it uses the base class's `object.__repr__` method, which returns a string that is hard to understand. | |
| +# So in that case we drop the key/value pair. | |
| +def _is_non_custom_str(key: Any) -> bool: | |
| + return type(key).__str__ is not object.__str__ or type(key).__repr__ is not object.__repr__ | |
| -# pylint: disable=too-many-return-statements | |
| -# pylint: disable=too-many-branches | |
| -def _clean_attribute( | |
| - key: str, value: types.AttributeValue, max_len: int | None | |
| -) -> types.AttributeValue | tuple[str | int | float, ...] | None: | |
| - """Checks if attribute value is valid and cleans it if required. | |
| +@overload | |
| +def _clean_attribute_value( | |
| + value: Mapping[str, types.AnyValue], | |
| + max_string_value_length: int | None, | |
| +) -> Mapping[str, types.AnyValue]: ... | |
| - The function returns the cleaned value or None if the value is not valid. | |
| - An attribute value is valid if it is either: | |
| - - A primitive type: string, boolean, double precision floating | |
| - point (IEEE 754-1985) or integer. | |
| - - An array of primitive type values. The array MUST be homogeneous, | |
| - i.e. it MUST NOT contain values of different types. | |
| +@overload | |
| +def _clean_attribute_value( | |
| + value: types.AnyValue, | |
| + max_string_value_length: int | None, | |
| +) -> types.AnyValue: ... | |
| - An attribute needs cleansing if: | |
| - - Its length is greater than the maximum allowed length. | |
| - - It needs to be encoded/decoded e.g, bytes to strings. | |
| - """ | |
| - if not (key and isinstance(key, str)): | |
| - _logger.warning("invalid key `%s`. must be non-empty string.", key) | |
| - return None | |
| - | |
| - if isinstance(value, _VALID_ATTR_VALUE_TYPES): | |
| - if isinstance(value, bytes): | |
| - try: | |
| - value = value.decode() | |
| - except UnicodeDecodeError: | |
| - _logger.warning("Byte attribute could not be decoded.") | |
| - return None | |
| - if max_len is not None and isinstance(value, str): | |
| - value = value[:max_len] | |
| - return value | |
| +def _clean_attribute_value( | |
| + value: types.AnyValue, | |
| + max_string_value_length: int | None, | |
| +) -> types.AnyValue: | |
| + """Recursively checks if an attribute value is valid and cleans it if required. | |
| - if isinstance(value, Sequence): | |
| - sequence_first_valid_type = None | |
| - cleaned_seq = [] | |
| - | |
| - for element in value: | |
| - if isinstance(element, bytes): | |
| - try: | |
| - element = element.decode() | |
| - except UnicodeDecodeError: | |
| - _logger.warning("Byte attribute could not be decoded.") | |
| - cleaned_seq.append(None) | |
| - continue | |
| - if max_len is not None and isinstance(element, str): | |
| - element = element[:max_len] | |
| - elif element is None: | |
| - cleaned_seq.append(None) | |
| - continue | |
| + String values are truncated to max_string_value_length if provided. | |
| + Anything that isn't of `types.AnyValue`, we attempt to cast to `str`. | |
| + If this fails, the value is replaced with None. Sequence's are converted to tuples and mappings | |
| + are copied into new dicts. | |
| - element_type = type(element) | |
| - # Reject attribute value if sequence contains a value with an incompatible type. | |
| - if element_type not in _VALID_ATTR_VALUE_TYPES: | |
| + Returns: | |
| + The recursively cleaned AnyValue. | |
| + """ | |
| + if isinstance(value, (NoneType, bool, int, float, bytes)): | |
| + return value | |
| + if isinstance(value, str): | |
| + if max_string_value_length is not None and len(value) > max_string_value_length: | |
| + _logger.warning( | |
| + "String attribute value exceeds max length of %d, truncating.", | |
| + max_string_value_length, | |
| + ) | |
| + value = value[:max_string_value_length] | |
| + return value | |
| + if isinstance(value, Sequence): | |
| + return tuple(_clean_attribute_value(v, max_string_value_length) for v in value) | |
| + if isinstance(value, Mapping): | |
| + cleaned_mapping: dict[str, types.AnyValue] = {} | |
| + for key, val in value.items(): | |
| + if not key: | |
| _logger.warning( | |
| - "Invalid type %s in attribute '%s' value sequence. Expected one of %s or None", | |
| - element_type.__name__, | |
| + "invalid attribute key `%s`. must be non-empty string. Dropping key from attributes.", | |
| key, | |
| - [valid_type.__name__ for valid_type in _VALID_ATTR_VALUE_TYPES], | |
| ) | |
| - return None | |
| - | |
| - # The type of the sequence must be homogeneous. The first non-None | |
| - # element determines the type of the sequence | |
| - if sequence_first_valid_type is None: | |
| - sequence_first_valid_type = element_type | |
| - # use equality instead of isinstance as isinstance(True, int) evaluates to True | |
| - elif element_type != sequence_first_valid_type: | |
| + continue | |
| + # Spec says to convert unknown types to strings if possible (here and below too). | |
| + if not isinstance(key, str): | |
| _logger.warning( | |
| - "Attribute %r mixes types %s and %s in attribute value sequence", | |
| + "Invalid type `%s` for attribute key `%s`, must be a str. Key's `__str__/__repr__` method will be called if it exists, otherwise the key/value pair will be dropped.", | |
| + type(key), | |
| key, | |
| - sequence_first_valid_type.__name__, | |
| - type(element).__name__, | |
| ) | |
| - return None | |
| - | |
| - cleaned_seq.append(element) | |
| - | |
| - # Freeze mutable sequences defensively | |
| - return tuple(cleaned_seq) | |
| - | |
| + if _is_non_custom_str(key): | |
| + key = str(key) | |
| + else: | |
| + continue | |
| + cleaned_mapping[key] = _clean_attribute_value(val, max_string_value_length) | |
| + return cleaned_mapping | |
| + if TYPE_CHECKING: | |
| + assert_never(value) | |
| _logger.warning( | |
| - "Invalid type %s for attribute '%s' value. Expected one of %s or a sequence of those types", | |
| - type(value).__name__, | |
| - key, | |
| - [valid_type.__name__ for valid_type in _VALID_ATTR_VALUE_TYPES], | |
| + "Invalid type `%s` for attribute value. Expected one of bool, str, None, bytes, int, float or a " | |
| + "Mapping or Sequence of those types. Value's __str__ method will be called if it exists, otherwise the value will be replaced with None.", | |
| + type(value), | |
| ) | |
| - return None | |
| - | |
| - | |
| -def _clean_extended_attribute_value( # pylint: disable=too-many-branches | |
| - value: types.AnyValue, max_len: int | None | |
| -) -> types.AnyValue: | |
| - # for primitive types just return the value and eventually shorten the string length | |
| - if value is None or isinstance(value, _VALID_ATTR_VALUE_TYPES): | |
| - if max_len is not None and isinstance(value, str): | |
| - value = value[:max_len] | |
| - return value | |
| - | |
| - if isinstance(value, Mapping): | |
| - cleaned_dict: dict[str, types.AnyValue] = {} | |
| - for key, element in value.items(): | |
| - # skip invalid keys | |
| - if not (key and isinstance(key, str)): | |
| - _logger.warning("invalid key `%s`. must be non-empty string.", key) | |
| - continue | |
| - | |
| - cleaned_dict[key] = _clean_extended_attribute(key=key, value=element, max_len=max_len) | |
| - | |
| - return cleaned_dict | |
| - | |
| - if isinstance(value, Sequence): | |
| - sequence_first_valid_type = None | |
| - cleaned_seq: list[types.AnyValue] = [] | |
| - | |
| - for element in value: | |
| - if element is None: | |
| - cleaned_seq.append(element) | |
| - continue | |
| - | |
| - if max_len is not None and isinstance(element, str): | |
| - element = element[:max_len] | |
| - | |
| - element_type = type(element) | |
| - if element_type not in _VALID_ATTR_VALUE_TYPES: | |
| - element = _clean_extended_attribute_value(element, max_len=max_len) | |
| - element_type = type(element) # type: ignore | |
| - | |
| - # The type of the sequence must be homogeneous. The first non-None | |
| - # element determines the type of the sequence | |
| - if sequence_first_valid_type is None: | |
| - sequence_first_valid_type = element_type | |
| - # use equality instead of isinstance as isinstance(True, int) evaluates to True | |
| - elif element_type != sequence_first_valid_type: | |
| - _logger.warning( | |
| - "Mixed types %s and %s in attribute value sequence", | |
| - sequence_first_valid_type.__name__, | |
| - type(element).__name__, | |
| - ) | |
| - return None | |
| - | |
| - cleaned_seq.append(element) | |
| - | |
| - # Freeze mutable sequences defensively | |
| - return tuple(cleaned_seq) | |
| - | |
| - # Some applications such as Django add values to log records whose types fall outside the | |
| - # primitive types and `_VALID_ANY_VALUE_TYPES`, i.e., they are not of type `AnyValue`. | |
| - # Rather than attempt to whitelist every possible instrumentation, we stringify those values here | |
| - # so they can still be represented as attributes, falling back to the original TypeError only if | |
| - # converting to string raises. | |
| - try: | |
| + if _is_non_custom_str(value): | |
| return str(value) | |
| - except Exception: | |
| - raise TypeError( | |
| - f"Invalid type {type(value).__name__} for attribute value. " | |
| - f"Expected one of {[_type_name(valid_type) for valid_type in _VALID_ANY_VALUE_TYPES]} or a " | |
| - "sequence of those types", | |
| - ) | |
| + return None | |
| -def _clean_extended_attribute(key: str, value: types.AnyValue, max_len: int | None) -> types.AnyValue: | |
| - """Checks if attribute value is valid and cleans it if required. | |
| +class BoundedAttributes(MutableMapping[str, types.AnyValue]): | |
| + """A dict with a fixed max capacity which cleans and potentially drops values to ensure they are valid attribute values. | |
| - The function returns the cleaned value or None if the value is not valid. | |
| + Args: | |
| + maxlen: The maximum number of attributes to store, use None for no limit. | |
| + attributes: The initial attributes to store. | |
| + immutable: Defaults to true. Whether to allow adding/removing of attributes after the initialisation of the instance. | |
| + max_value_len: The maximum length of string values, use None for no limit. | |
| + extended_attributes: Deprecated. Kept for backwards compatibility. Extended attributes are now always used for attributes everywhere. | |
| - An attribute value is valid if it is an AnyValue. | |
| - An attribute needs cleansing if: | |
| - - Its length is greater than the maximum allowed length. | |
| + When the dict is full and a new element is added, the oldest element is dropped. Attributes are made to be immutable when set in this container. | |
| + So passing a mutable list as an attribute value, and then mutating it after will not change it's value in this container. | |
| """ | |
| - if not (key and isinstance(key, str)): | |
| - _logger.warning("invalid key `%s`. must be non-empty string.", key) | |
| - return None | |
| - | |
| - try: | |
| - return _clean_extended_attribute_value(value, max_len=max_len) | |
| - except TypeError as exception: | |
| - _logger.warning("Attribute %s: %s", key, exception) | |
| - return None | |
| - | |
| - | |
| -class BoundedAttributes(MutableMapping): # type: ignore | |
| - """An ordered dict with a fixed max capacity. | |
| + @overload | |
| + def __init__( | |
| + self, | |
| + maxlen: int | None = None, | |
| + attributes: types.Attributes = None, | |
| + immutable: bool = True, | |
| + max_value_len: int | None = None, | |
| + ) -> None: ... | |
| - Oldest elements are dropped when the dict is full and a new element is | |
| - added. | |
| - """ | |
| + @overload | |
| + @deprecated( | |
| + "Creating BoundedAttributes with `extended_attributes` set is deprecated. " | |
| + "The `extended_attributes` param is no longer used and will be removed " | |
| + "in a future release. Extended attributes are now always used for attributes everywhere." | |
| + ) | |
| + def __init__( | |
| + self, | |
| + maxlen: int | None = None, | |
| + attributes: types.Attributes = None, | |
| + immutable: bool = True, | |
| + max_value_len: int | None = None, | |
| + extended_attributes: bool = False, | |
| + ) -> None: ... | |
| def __init__( | |
| self, | |
| maxlen: int | None = None, | |
| - attributes: types._ExtendedAttributes | None = None, | |
| + attributes: types.Attributes = None, | |
| immutable: bool = True, | |
| max_value_len: int | None = None, | |
| extended_attributes: bool = False, | |
| - ): | |
| - if maxlen is not None: | |
| - if not isinstance(maxlen, int) or maxlen < 0: | |
| - raise ValueError("maxlen must be valid int greater or equal to 0") | |
| + ) -> None: | |
| + if maxlen is not None and maxlen < 0: | |
| + raise ValueError("maxlen must be valid int greater or equal to 0") | |
| + self._dict: dict[str, types.AnyValue] = {} | |
| self.maxlen = maxlen | |
| self.dropped = 0 | |
| self.max_value_len = max_value_len | |
| - self._extended_attributes = extended_attributes | |
| - # OrderedDict is not used until the maxlen is reached for efficiency. | |
| - | |
| - self._dict: MutableMapping[str, types.AnyValue] | OrderedDict[str, types.AnyValue] = {} | |
| self._lock = threading.Lock() | |
| + # setting False before adding items | |
| + self._immutable = False | |
| if attributes: | |
| - for key, value in attributes.items(): | |
| - self[key] = value | |
| + self._set_items(attributes) | |
| self._immutable = immutable | |
| def __repr__(self) -> str: | |
| class BoundedAttributes(MutableMapping): # type: ignore | |
| def __getitem__(self, key: str) -> types.AnyValue: | |
| return self._dict[key] | |
| + def _raise_if_immutable(self) -> None: | |
| + if self._immutable: | |
| + raise TypeError("Cannot mutate immutable BoundedAttributes") | |
| + | |
| def __setitem__(self, key: str, value: types.AnyValue) -> None: | |
| - if getattr(self, "_immutable", False): # type: ignore | |
| - raise TypeError | |
| + self._raise_if_immutable() | |
| if self.maxlen is not None and self.maxlen == 0: | |
| with self._lock: | |
| self.dropped += 1 | |
| - return | |
| - if self._extended_attributes: | |
| - value = _clean_extended_attribute(key, value, self.max_value_len) | |
| - else: | |
| - value = _clean_attribute(key, value, self.max_value_len) # type: ignore | |
| - if value is None: | |
| return | |
| + if not key or not isinstance(key, str): | |
| + _logger.warning( | |
| + "invalid key `%s`. must be non-empty string. Dropping key from attributes.", | |
| + key, | |
| + ) | |
| + with self._lock: | |
| + self.dropped += 1 | |
| + return | |
| + cleaned = _clean_attribute_value(value, self.max_value_len) | |
| with self._lock: | |
| - self._setitem_locked(key, value) | |
| + self._setitem_locked(key, cleaned) | |
| - def _set_items(self, attributes: "types._ExtendedAttributes") -> None: | |
| - if getattr(self, "_immutable", False): # type: ignore | |
| - raise TypeError | |
| + def _set_items(self, attributes: Mapping[str, types.AnyValue]) -> None: | |
| + self._raise_if_immutable() | |
| if self.maxlen is not None and self.maxlen == 0: | |
| with self._lock: | |
| self.dropped += len(attributes) | |
| return | |
| - cleaned = [] | |
| - for key, value in attributes.items(): | |
| - if self._extended_attributes: | |
| - cv = _clean_extended_attribute(key, value, self.max_value_len) | |
| - else: | |
| - cv = _clean_attribute(key, value, self.max_value_len) # type: ignore | |
| - if cv is None: | |
| - continue | |
| - cleaned.append((key, cv)) | |
| + cleaned_attributes: Mapping[str, types.AnyValue] = _clean_attribute_value(attributes, self.max_value_len) | |
| with self._lock: | |
| - for key, cv in cleaned: | |
| - self._setitem_locked(key, cv) | |
| + self.dropped += len(attributes) - len(cleaned_attributes) | |
| + for key, value in cleaned_attributes.items(): | |
| + self._setitem_locked(key, value) | |
| def _setitem_locked(self, key: str, value: types.AnyValue) -> None: | |
| if key in self._dict: | |
| del self._dict[key] | |
| - elif self.maxlen is not None and len(self._dict) == self.maxlen: | |
| - if not isinstance(self._dict, OrderedDict): | |
| - self._dict = OrderedDict(self._dict) | |
| - self._dict.popitem(last=False) # type: ignore | |
| + if self.maxlen is not None and len(self._dict) >= self.maxlen: | |
| + _logger.warning( | |
| + "Attributes dict is full. Dropping the oldest key-value pair from attributes to make space for the new key-value pair.", | |
| + ) | |
| + # Dictionaries are insertion ordered in Python, this is the recommended way to get the oldest value. | |
| + del self._dict[next(iter(self._dict.keys()))] | |
| self.dropped += 1 | |
| - self._dict[key] = value # type: ignore | |
| + self._dict[key] = value | |
| def __delitem__(self, key: str) -> None: | |
| - if getattr(self, "_immutable", False): # type: ignore | |
| - raise TypeError | |
| - with self._lock: | |
| - del self._dict[key] | |
| + self._raise_if_immutable() | |
| + del self._dict[key] | |
| def __iter__(self): | |
| if self._immutable: | |
| class BoundedAttributes(MutableMapping): # type: ignore | |
| def __len__(self) -> int: | |
| return len(self._dict) | |
| - def __deepcopy__(self, memo: dict) -> "BoundedAttributes": | |
| + def __deepcopy__(self, memo: dict[int, Any]) -> "BoundedAttributes": | |
| copy_ = BoundedAttributes( | |
| maxlen=self.maxlen, | |
| immutable=self._immutable, | |
| max_value_len=self.max_value_len, | |
| - extended_attributes=self._extended_attributes, | |
| ) | |
| memo[id(self)] = copy_ | |
| with self._lock: | |
| class BoundedAttributes(MutableMapping): # type: ignore | |
| copy_.dropped = self.dropped | |
| return copy_ | |
| - def copy(self): # type: ignore | |
| - return self._dict.copy() # type: ignore | |
| + def copy(self) -> MutableMapping[str, types.AnyValue]: | |
| + return self._dict.copy() | |
| diff --git a/opentelemetry-api/src/opentelemetry/metrics/_internal/__init__.py b/opentelemetry-api/src/opentelemetry/metrics/_internal/__init__.py | |
| index ed1bb750..183966b1 100644 | |
| --- a/opentelemetry-api/src/opentelemetry/metrics/_internal/__init__.py | |
| +++ b/opentelemetry-api/src/opentelemetry/metrics/_internal/__init__.py | |
| class MeterProvider(ABC): | |
| name: str, | |
| version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> "Meter": | |
| """Returns a `Meter` for use by the given instrumentation library. | |
| class NoOpMeterProvider(MeterProvider): | |
| name: str, | |
| version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> "Meter": | |
| """Returns a NoOpMeter.""" | |
| return NoOpMeter(name, version=version, schema_url=schema_url) | |
| class _ProxyMeterProvider(MeterProvider): | |
| name: str, | |
| version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> "Meter": | |
| with self._lock: | |
| if self._real_meter_provider is not None: | |
| def get_meter( | |
| version: str = "", | |
| meter_provider: MeterProvider | None = None, | |
| schema_url: str | None = None, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> "Meter": | |
| """Returns a `Meter` for use by the given instrumentation library. | |
| diff --git a/opentelemetry-api/src/opentelemetry/metrics/_internal/instrument.py b/opentelemetry-api/src/opentelemetry/metrics/_internal/instrument.py | |
| index 7e27e520..bccdbc30 100644 | |
| --- a/opentelemetry-api/src/opentelemetry/metrics/_internal/instrument.py | |
| +++ b/opentelemetry-api/src/opentelemetry/metrics/_internal/instrument.py | |
| class Counter(Synchronous): | |
| def add( | |
| self, | |
| amount: int | float, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ) -> None: | |
| """Records an increment to the counter. | |
| class NoOpCounter(Counter): | |
| def add( | |
| self, | |
| amount: int | float, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ) -> None: | |
| return super().add(amount, attributes=attributes, context=context) | |
| class _ProxyCounter(_ProxyInstrument[Counter], Counter): | |
| def add( | |
| self, | |
| amount: int | float, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ) -> None: | |
| if self._real_instrument: | |
| class UpDownCounter(Synchronous): | |
| def add( | |
| self, | |
| amount: int | float, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ) -> None: | |
| """Records an increment or decrement to the counter. | |
| class NoOpUpDownCounter(UpDownCounter): | |
| def add( | |
| self, | |
| amount: int | float, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ) -> None: | |
| return super().add(amount, attributes=attributes, context=context) | |
| class _ProxyUpDownCounter(_ProxyInstrument[UpDownCounter], UpDownCounter): | |
| def add( | |
| self, | |
| amount: int | float, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ) -> None: | |
| if self._real_instrument: | |
| class Histogram(Synchronous): | |
| def record( | |
| self, | |
| amount: int | float, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ) -> None: | |
| """Records a measurement. | |
| class NoOpHistogram(Histogram): | |
| def record( | |
| self, | |
| amount: int | float, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ) -> None: | |
| return super().record(amount, attributes=attributes, context=context) | |
| class _ProxyHistogram(_ProxyInstrument[Histogram], Histogram): | |
| def record( | |
| self, | |
| amount: int | float, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ) -> None: | |
| if self._real_instrument: | |
| class Gauge(Synchronous): | |
| def set( | |
| self, | |
| amount: int | float, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ) -> None: | |
| """Records the current value of the gauge. | |
| class NoOpGauge(Gauge): | |
| def set( | |
| self, | |
| amount: int | float, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ) -> None: | |
| return super().set(amount, attributes=attributes, context=context) | |
| class _ProxyGauge( | |
| def set( | |
| self, | |
| amount: int | float, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ) -> None: | |
| if self._real_instrument: | |
| diff --git a/opentelemetry-api/src/opentelemetry/trace/__init__.py b/opentelemetry-api/src/opentelemetry/trace/__init__.py | |
| index 47aaac84..b705b404 100644 | |
| --- a/opentelemetry-api/src/opentelemetry/trace/__init__.py | |
| +++ b/opentelemetry-api/src/opentelemetry/trace/__init__.py | |
| class TracerProvider(ABC): | |
| instrumenting_module_name: str, | |
| instrumenting_library_version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: types.Attributes | None = None, | |
| + attributes: types.Attributes = None, | |
| ) -> "Tracer": | |
| """Returns a `Tracer` for use by the given instrumentation library. | |
| class NoOpTracerProvider(TracerProvider): | |
| instrumenting_module_name: str, | |
| instrumenting_library_version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: types.Attributes | None = None, | |
| + attributes: types.Attributes = None, | |
| ) -> "Tracer": | |
| # pylint:disable=no-self-use,unused-argument | |
| return NoOpTracer() | |
| class ProxyTracerProvider(TracerProvider): | |
| instrumenting_module_name: str, | |
| instrumenting_library_version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: types.Attributes | None = None, | |
| + attributes: types.Attributes = None, | |
| ) -> "Tracer": | |
| if _TRACER_PROVIDER: | |
| return _TRACER_PROVIDER.get_tracer( | |
| class ProxyTracer(Tracer): | |
| instrumenting_module_name: str, | |
| instrumenting_library_version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: types.Attributes | None = None, | |
| + attributes: types.Attributes = None, | |
| ): | |
| self._instrumenting_module_name = instrumenting_module_name | |
| self._instrumenting_library_version = instrumenting_library_version | |
| def get_tracer( | |
| instrumenting_library_version: str | None = None, | |
| tracer_provider: TracerProvider | None = None, | |
| schema_url: str | None = None, | |
| - attributes: types.Attributes | None = None, | |
| + attributes: types.Attributes = None, | |
| ) -> "Tracer": | |
| """Returns a `Tracer` for use by the given instrumentation library. | |
| diff --git a/opentelemetry-api/src/opentelemetry/trace/span.py b/opentelemetry-api/src/opentelemetry/trace/span.py | |
| index 745f4f5f..a68489c8 100644 | |
| --- a/opentelemetry-api/src/opentelemetry/trace/span.py | |
| +++ b/opentelemetry-api/src/opentelemetry/trace/span.py | |
| class Span(abc.ABC): | |
| """ | |
| @abc.abstractmethod | |
| - def set_attributes(self, attributes: Mapping[str, types.AttributeValue]) -> None: | |
| + def set_attributes(self, attributes: Mapping[str, types.AnyValue]) -> None: | |
| """Sets Attributes. | |
| Sets Attributes with the key and value passed as arguments dict. | |
| class Span(abc.ABC): | |
| """ | |
| @abc.abstractmethod | |
| - def set_attribute(self, key: str, value: types.AttributeValue) -> None: | |
| + def set_attribute(self, key: str, value: types.AnyValue) -> None: | |
| """Sets an Attribute. | |
| Sets a single Attribute with the key and value passed as arguments. | |
| class NonRecordingSpan(Span): | |
| def end(self, end_time: int | None = None) -> None: | |
| pass | |
| - def set_attributes(self, attributes: Mapping[str, types.AttributeValue]) -> None: | |
| + def set_attributes(self, attributes: Mapping[str, types.AnyValue]) -> None: | |
| pass | |
| - def set_attribute(self, key: str, value: types.AttributeValue) -> None: | |
| + def set_attribute(self, key: str, value: types.AnyValue) -> None: | |
| pass | |
| def add_event( | |
| diff --git a/opentelemetry-api/src/opentelemetry/util/types.py b/opentelemetry-api/src/opentelemetry/util/types.py | |
| index 1e8e74a3..4456a47f 100644 | |
| --- a/opentelemetry-api/src/opentelemetry/util/types.py | |
| +++ b/opentelemetry-api/src/opentelemetry/util/types.py | |
| from collections.abc import Mapping, Sequence | |
| # This is the implementation of the "Any" type as specified by the specifications of OpenTelemetry data model for logs. | |
| # For more details, refer to the OTel specification: | |
| # https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/logs/data-model.md#type-any | |
| -AnyValue = str | bool | int | float | bytes | Sequence["AnyValue"] | Mapping[str, "AnyValue"] | None | |
| +AnyValue = AttributeValue = str | bool | int | float | bytes | Sequence["AnyValue"] | Mapping[str, "AnyValue"] | None | |
| +Attributes = Mapping[str, AnyValue] | None | |
| -AttributeValue = str | bool | int | float | Sequence[str] | Sequence[bool] | Sequence[int] | Sequence[float] | |
| -Attributes = Mapping[str, AttributeValue] | None | |
| +# Deprecated type, do not use. | |
| AttributesAsKey = tuple[ | |
| tuple[ | |
| str, | |
| AttributesAsKey = tuple[ | |
| ], | |
| ..., | |
| ] | |
| - | |
| -_ExtendedAttributes = Mapping[str, "AnyValue"] | |
| diff --git a/opentelemetry-api/tests/attributes/test_attributes.py b/opentelemetry-api/tests/attributes/test_attributes.py | |
| index eb210b27..29e98264 100644 | |
| --- a/opentelemetry-api/tests/attributes/test_attributes.py | |
| +++ b/opentelemetry-api/tests/attributes/test_attributes.py | |
| import logging | |
| import threading | |
| import unittest | |
| import unittest.mock | |
| -from collections.abc import MutableSequence | |
| from opentelemetry.attributes import ( | |
| BoundedAttributes, | |
| - _clean_attribute, | |
| - _clean_extended_attribute, | |
| - _clean_extended_attribute_value, | |
| + _clean_attribute_value, | |
| ) | |
| -class TestAttributes(unittest.TestCase): | |
| - # pylint: disable=invalid-name | |
| - def assertValid(self, value, key="k"): | |
| - expected = value | |
| - if isinstance(value, MutableSequence): | |
| - expected = tuple(value) | |
| - self.assertEqual(_clean_attribute(key, value, None), expected) | |
| - | |
| - def assertInvalid(self, value, key="k"): | |
| - self.assertIsNone(_clean_attribute(key, value, None)) | |
| - | |
| - def test_attribute_key_validation(self): | |
| - # only non-empty strings are valid keys | |
| - self.assertInvalid(1, "") | |
| - self.assertInvalid(1, 1) | |
| - self.assertInvalid(1, {}) | |
| - self.assertInvalid(1, []) | |
| - self.assertInvalid(1, b"1") | |
| - self.assertValid(1, "k") | |
| - self.assertValid(1, "1") | |
| - | |
| - def test_clean_attribute(self): | |
| - self.assertInvalid([1, 2, 3.4, "ss", 4]) | |
| - self.assertInvalid([{}, 1, 2, 3.4, 4]) | |
| - self.assertInvalid(["sw", "lf", 3.4, "ss"]) | |
| - self.assertInvalid([1, 2, 3.4, 5]) | |
| - self.assertInvalid({}) | |
| - self.assertInvalid([1, True]) | |
| - self.assertValid(True) | |
| - self.assertValid("hi") | |
| - self.assertValid(3.4) | |
| - self.assertValid(15) | |
| - self.assertValid([1, 2, 3, 5]) | |
| - self.assertValid([1.2, 2.3, 3.4, 4.5]) | |
| - self.assertValid([True, False]) | |
| - self.assertValid(["ss", "dw", "fw"]) | |
| - self.assertValid([]) | |
| - # None in sequences are valid | |
| - self.assertValid(["A", None, None]) | |
| - self.assertValid(["A", None, None, "B"]) | |
| - self.assertValid([None, None]) | |
| - self.assertInvalid(["A", None, 1]) | |
| - self.assertInvalid([None, "A", None, 1]) | |
| - | |
| - # test keys | |
| - self.assertValid("value", "key") | |
| - self.assertInvalid("value", "") | |
| - self.assertInvalid("value", None) | |
| - | |
| - def test_sequence_attr_decode(self): | |
| - seq = [ | |
| - None, | |
| - b"Content-Disposition", | |
| - b"Content-Type", | |
| - b"\x81", | |
| - b"Keep-Alive", | |
| - ] | |
| - expected = [ | |
| - None, | |
| - "Content-Disposition", | |
| - "Content-Type", | |
| - None, | |
| - "Keep-Alive", | |
| - ] | |
| - self.assertEqual(_clean_attribute("headers", seq, None), tuple(expected)) | |
| - | |
| - | |
| -class TestExtendedAttributes(unittest.TestCase): | |
| - # pylint: disable=invalid-name | |
| - def assertValid(self, value, key="k"): | |
| - expected = value | |
| - if isinstance(value, MutableSequence): | |
| - expected = tuple(value) | |
| - self.assertEqual(_clean_extended_attribute(key, value, None), expected) | |
| - | |
| - def assertInvalid(self, value, key="k"): | |
| - self.assertIsNone(_clean_extended_attribute(key, value, None)) | |
| - | |
| - def test_attribute_key_validation(self): | |
| - # only non-empty strings are valid keys | |
| - self.assertInvalid(1, "") | |
| - self.assertInvalid(1, 1) | |
| - self.assertInvalid(1, {}) | |
| - self.assertInvalid(1, []) | |
| - self.assertInvalid(1, b"1") | |
| - self.assertValid(1, "k") | |
| - self.assertValid(1, "1") | |
| - | |
| - def test_clean_extended_attribute(self): | |
| - self.assertInvalid([1, 2, 3.4, "ss", 4]) | |
| - self.assertInvalid([{}, 1, 2, 3.4, 4]) | |
| - self.assertInvalid(["sw", "lf", 3.4, "ss"]) | |
| - self.assertInvalid([1, 2, 3.4, 5]) | |
| - self.assertInvalid([1, True]) | |
| - self.assertValid(None) | |
| - self.assertValid(True) | |
| - self.assertValid("hi") | |
| - self.assertValid(3.4) | |
| - self.assertValid(15) | |
| - self.assertValid([1, 2, 3, 5]) | |
| - self.assertValid([1.2, 2.3, 3.4, 4.5]) | |
| - self.assertValid([True, False]) | |
| - self.assertValid(["ss", "dw", "fw"]) | |
| - self.assertValid([]) | |
| - # None in sequences are valid | |
| - self.assertValid(["A", None, None]) | |
| - self.assertValid(["A", None, None, "B"]) | |
| - self.assertValid([None, None]) | |
| - self.assertInvalid(["A", None, 1]) | |
| - self.assertInvalid([None, "A", None, 1]) | |
| - # mappings | |
| - self.assertValid({}) | |
| - self.assertValid({"k": "v"}) | |
| - # mappings in sequences | |
| - self.assertValid([{"k": "v"}]) | |
| - | |
| - # test keys | |
| - self.assertValid("value", "key") | |
| - self.assertInvalid("value", "") | |
| - self.assertInvalid("value", None) | |
| - | |
| - def test_sequence_attr_decode(self): | |
| - seq = [ | |
| - None, | |
| - b"Content-Disposition", | |
| - b"Content-Type", | |
| - b"\x81", | |
| - b"Keep-Alive", | |
| - ] | |
| - self.assertEqual(_clean_extended_attribute("headers", seq, None), tuple(seq)) | |
| - | |
| - def test_mapping(self): | |
| - mapping = { | |
| - "": "invalid", | |
| - b"bytes": "invalid", | |
| - "none": {"": "invalid"}, | |
| - "valid_primitive": "str", | |
| - "valid_sequence": ["str"], | |
| - "invalid_sequence": ["str", 1], | |
| - "valid_mapping": {"str": 1}, | |
| - "invalid_mapping": {"": 1}, | |
| - } | |
| - expected = { | |
| - "none": {}, | |
| - "valid_primitive": "str", | |
| - "valid_sequence": ("str",), | |
| - "invalid_sequence": None, | |
| - "valid_mapping": {"str": 1}, | |
| - "invalid_mapping": {}, | |
| - } | |
| - self.assertEqual(_clean_extended_attribute("headers", mapping, None), expected) | |
| +class _NoStrNoReprObject: | |
| + def __init__(self): | |
| + pass | |
| class TestBoundedAttributes(unittest.TestCase): | |
| class TestBoundedAttributes(unittest.TestCase): | |
| "vaccinated": True, | |
| } | |
| - def test_negative_maxlen(self): | |
| + def test_clean_attribute_value_with_various_params(self): | |
| + # A python object that isn't a primitive and has no string/repr method is converted to None. | |
| + with self.assertLogs("opentelemetry", level="WARNING") as cm: | |
| + self.assertEqual( | |
| + _clean_attribute_value(_NoStrNoReprObject(), None), | |
| + None, | |
| + ) | |
| + self.assertEqual(len(cm.output), 1) | |
| + self.assertIn("Expected one of bool, str, None, bytes, int, float", cm.output[0]) | |
| + | |
| + valid_primitive_sequence = [1, 2.2, None, "cookie"] | |
| + self.assertEqual( | |
| + _clean_attribute_value(valid_primitive_sequence, None), | |
| + tuple(valid_primitive_sequence), | |
| + ) | |
| + for valid_primitive in valid_primitive_sequence: | |
| + self.assertEqual(_clean_attribute_value(valid_primitive, None), valid_primitive) | |
| + | |
| + self.assertEqual(_clean_attribute_value(b"hello", 4), b"hello") | |
| + | |
| + with self.assertLogs("opentelemetry", level="WARNING") as cm: | |
| + # String is truncated. | |
| + self.assertEqual(_clean_attribute_value("a" * 1000, 5), "aaaaa") | |
| + self.assertEqual(len(cm.output), 1) | |
| + self.assertIn("String attribute value exceeds max length", cm.output[0]) | |
| + | |
| + # Sequence of different types of values. List converted to tuple. | |
| + self.assertEqual( | |
| + _clean_attribute_value(["a", 2, _NoStrNoReprObject(), None, b"\xff"], None), | |
| + ("a", 2, None, None, b"\xff"), | |
| + ) | |
| + | |
| + # non-str key in map... will be converted to string | |
| + with self.assertLogs("opentelemetry", level="WARNING") as cm: | |
| + self.assertEqual(_clean_attribute_value({2.2: 4.4}, None), {"2.2": 4.4}) | |
| + self.assertEqual(len(cm.output), 1) | |
| + self.assertIn( | |
| + "Invalid type", | |
| + cm.output[0], | |
| + ) | |
| + | |
| + # Mapping of values.. | |
| + # Non string key without a string conversion method is dropped. | |
| + self.assertEqual( | |
| + _clean_attribute_value( | |
| + { | |
| + "a": 1, | |
| + _NoStrNoReprObject(): 2, | |
| + "c": 3, | |
| + "d": [2, 3], | |
| + "bytes": b"\xff", | |
| + }, | |
| + None, | |
| + ), | |
| + {"a": 1, "c": 3, "d": (2, 3), "bytes": b"\xff"}, | |
| + ) | |
| + | |
| + def test_same_key_value_overwritten(self): | |
| + bdict = BoundedAttributes(1, {"name": "Firulais"}, immutable=False) | |
| + self.assertEqual(bdict["name"], "Firulais") | |
| + self.assertEqual(bdict.dropped, 0) | |
| + bdict["name"] = "Bruno" | |
| + self.assertEqual(bdict["name"], "Bruno") | |
| + self.assertEqual(bdict.dropped, 0) | |
| + | |
| + def test_invalid_key_not_used(self): | |
| + bdict = BoundedAttributes(50, {}, immutable=False) | |
| + with self.assertLogs("opentelemetry", level="WARNING") as cm: | |
| + bdict[1] = 2 | |
| + self.assertEqual(len(cm.output), 1) | |
| + self.assertIn("invalid key", cm.output[0]) | |
| + self.assertNotIn(1, bdict) | |
| + self.assertEqual(bdict.dropped, 1) | |
| + | |
| + def test_maxlen_reached(self): | |
| + bdict = BoundedAttributes(1, {"first": "value"}, immutable=False) | |
| + with self.assertLogs("opentelemetry", level="WARNING") as cm: | |
| + bdict["second"] = "another" | |
| + self.assertIn("Attributes dict is full. Dropping the oldest", cm.output[0]) | |
| + self.assertNotIn("first", bdict) | |
| + self.assertEqual(bdict["second"], "another") | |
| + self.assertEqual(bdict.dropped, 1) | |
| + | |
| + def test_negative_maxlen_not_allowed(self): | |
| with self.assertRaises(ValueError): | |
| BoundedAttributes(-1) | |
| - def test_from_map(self): | |
| + def test_base_copy_isolated_and_len_works(self): | |
| dic_len = len(self.base) | |
| base_copy = self.base.copy() | |
| bdict = BoundedAttributes(dic_len, base_copy) | |
| class TestBoundedAttributes(unittest.TestCase): | |
| # test that iter yields the correct number of elements | |
| self.assertEqual(len(tuple(bdict)), dic_len) | |
| - # map too big | |
| - half_len = dic_len // 2 | |
| - bdict = BoundedAttributes(half_len, self.base) | |
| - self.assertEqual(len(tuple(bdict)), half_len) | |
| - self.assertEqual(bdict.dropped, dic_len - half_len) | |
| - | |
| - def test_bounded_dict(self): | |
| + def test_basic_insertion_update_iteration_and_deletion(self): | |
| # create empty dict | |
| dic_len = len(self.base) | |
| bdict = BoundedAttributes(dic_len, immutable=False) | |
| class TestBoundedAttributes(unittest.TestCase): | |
| bdict["name"] = "Bruno" | |
| self.assertEqual(bdict.dropped, 0) | |
| - # try to append more elements | |
| + # try to append more elements, old elements should be dropped | |
| for key in self.base: | |
| bdict["new-" + key] = self.base[key] | |
| self.assertEqual(len(bdict), dic_len) | |
| self.assertEqual(bdict.dropped, dic_len) | |
| - # Invalid values shouldn't be considered for `dropped` | |
| - bdict["invalid-seq"] = [None, 1, "2"] | |
| - self.assertEqual(bdict.dropped, dic_len) | |
| # test that elements in the dict are the new ones | |
| for key in self.base: | |
| class TestBoundedAttributes(unittest.TestCase): | |
| with self.assertRaises(KeyError): | |
| _ = bdict["new-name"] | |
| - def test_no_limit_code(self): | |
| - bdict = BoundedAttributes(maxlen=None, immutable=False) | |
| - for num in range(100): | |
| - bdict[str(num)] = num | |
| - | |
| - for num in range(100): | |
| - self.assertEqual(bdict[str(num)], num) | |
| - | |
| def test_immutable(self): | |
| bdict = BoundedAttributes() | |
| with self.assertRaises(TypeError): | |
| class TestBoundedAttributes(unittest.TestCase): | |
| With _clean_attribute called before the lock is acquired, no deadlock | |
| occurs. | |
| """ | |
| - bdict = BoundedAttributes(immutable=False) | |
| + bdict = BoundedAttributes(immutable=False, max_value_len=20) | |
| class ReentrantHandler(logging.Handler): | |
| def emit(self, _record): | |
| class TestBoundedAttributes(unittest.TestCase): | |
| completed = threading.Event() | |
| def run(): | |
| - # None is an invalid attribute value and triggers _logger.warning | |
| - # in _clean_attribute, which fires the ReentrantHandler above. | |
| - bdict["trigger.key"] = None | |
| + # A string value > 20 triggers a warning log in _clean_attribute, which fires the ReentrantHandler above. | |
| + bdict["trigger.key"] = "a" * 21 | |
| completed.set() | |
| thread = threading.Thread(target=run, daemon=True) | |
| class TestBoundedAttributes(unittest.TestCase): | |
| finally: | |
| otel_logger.removeHandler(handler) | |
| - # pylint: disable=no-self-use | |
| - def test_extended_attributes(self): | |
| - bdict = BoundedAttributes(extended_attributes=True, immutable=False) | |
| - with unittest.mock.patch( | |
| - "opentelemetry.attributes._clean_extended_attribute", | |
| - return_value="mock_value", | |
| - ) as clean_extended_attribute_mock: | |
| - bdict["key"] = "value" | |
| - | |
| - clean_extended_attribute_mock.assert_called_once() | |
| - | |
| def test_wsgi_request_conversion_to_string(self): | |
| - """Test that WSGI request objects are converted to strings when _clean_extended_attribute is called.""" | |
| + """Test that WSGI request objects are converted to strings when _clean_attribute_value is called.""" | |
| class DummyWSGIRequest: | |
| def __str__(self): | |
| return "<DummyWSGIRequest method=GET path=/example/>" | |
| - wsgi_request = DummyWSGIRequest() | |
| - | |
| - cleaned_value = _clean_extended_attribute("request", wsgi_request, None) | |
| - | |
| - # Verify we get a string back from the cleaner | |
| - self.assertIsInstance(cleaned_value, str) | |
| - self.assertEqual("<DummyWSGIRequest method=GET path=/example/>", cleaned_value) | |
| - | |
| - def test_invalid_anyvalue_type_raises_typeerror(self): | |
| - class BadStr: | |
| - def __str__(self): | |
| - raise RuntimeError("boom") | |
| - | |
| - with self.assertRaises(TypeError): | |
| - _clean_extended_attribute_value(BadStr(), None) | |
| + self.assertEqual( | |
| + "<DummyWSGIRequest method=GET path=/example/>", | |
| + _clean_attribute_value(DummyWSGIRequest(), None), | |
| + ) | |
| def test_deepcopy(self): | |
| bdict = BoundedAttributes(4, self.base, immutable=False) | |
| diff --git a/opentelemetry-api/tests/logs/test_proxy.py b/opentelemetry-api/tests/logs/test_proxy.py | |
| index c3c3519d..876d659c 100644 | |
| --- a/opentelemetry-api/tests/logs/test_proxy.py | |
| +++ b/opentelemetry-api/tests/logs/test_proxy.py | |
| from unittest.mock import Mock | |
| import opentelemetry._logs._internal as _logs_internal | |
| from opentelemetry import _logs | |
| from opentelemetry.test.globals_test import LoggingGlobalsTest | |
| -from opentelemetry.util.types import _ExtendedAttributes | |
| +from opentelemetry.util.types import Attributes | |
| class TestProvider(_logs.NoOpLoggerProvider): | |
| class TestProvider(_logs.NoOpLoggerProvider): | |
| name: str, | |
| version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> _logs.Logger: | |
| return LoggerTest(name) | |
| diff --git a/opentelemetry-api/tests/trace/test_proxy.py b/opentelemetry-api/tests/trace/test_proxy.py | |
| index 13f380c7..8d4ee165 100644 | |
| --- a/opentelemetry-api/tests/trace/test_proxy.py | |
| +++ b/opentelemetry-api/tests/trace/test_proxy.py | |
| class TestProvider(trace.NoOpTracerProvider): | |
| instrumenting_module_name: str, | |
| instrumenting_library_version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> trace.Tracer: | |
| return TestTracer() | |
| diff --git a/opentelemetry-configuration/src/opentelemetry/configuration/_resource.py b/opentelemetry-configuration/src/opentelemetry/configuration/_resource.py | |
| index a150a261..0cd804dc 100644 | |
| --- a/opentelemetry-configuration/src/opentelemetry/configuration/_resource.py | |
| +++ b/opentelemetry-configuration/src/opentelemetry/configuration/_resource.py | |
| from opentelemetry.sdk.resources import ( | |
| ServiceInstanceIdResourceDetector, | |
| _HostResourceDetector, | |
| ) | |
| -from opentelemetry.util.types import AttributeValue | |
| +from opentelemetry.util.types import AnyValue | |
| _logger = logging.getLogger(__name__) | |
| def create_resource(config: ResourceConfig | None) -> Resource: | |
| return result.merge(config_resource) | |
| -def _detect_service(_config: Any) -> dict[str, AttributeValue]: | |
| +def _detect_service(_config: Any) -> dict[str, AnyValue]: | |
| """Service detector: generates instance ID and reads OTEL_SERVICE_NAME.""" | |
| - attrs: dict[str, AttributeValue] = dict(ServiceInstanceIdResourceDetector().detect().attributes) | |
| + attrs: dict[str, AnyValue] = dict(ServiceInstanceIdResourceDetector().detect().attributes) | |
| if service_name := os.environ.get(OTEL_SERVICE_NAME): | |
| attrs[SERVICE_NAME] = service_name | |
| return attrs | |
| -_RESOURCE_DETECTOR_REGISTRY: dict[str, Callable[[Any], dict[str, AttributeValue]]] = { | |
| +_RESOURCE_DETECTOR_REGISTRY: dict[str, Callable[[Any], dict[str, AnyValue]]] = { | |
| "service": _detect_service, | |
| "host": lambda _: dict(_HostResourceDetector().detect().attributes), | |
| "process": lambda _: dict(ProcessResourceDetector().detect().attributes), | |
| diff --git a/opentelemetry-sdk/benchmarks/metrics/test_benchmark_metrics_histogram.py b/opentelemetry-sdk/benchmarks/metrics/test_benchmark_metrics_histogram.py | |
| index 440a37fc..746e62eb 100644 | |
| --- a/opentelemetry-sdk/benchmarks/metrics/test_benchmark_metrics_histogram.py | |
| +++ b/opentelemetry-sdk/benchmarks/metrics/test_benchmark_metrics_histogram.py | |
| # SPDX-License-Identifier: Apache-2.0 | |
| # pylint: disable=invalid-name | |
| +import json | |
| import random | |
| import pytest | |
| def test_histogram_record_10(benchmark, num_labels): | |
| benchmark(benchmark_histogram_record_10) | |
| +@pytest.mark.parametrize("num_labels", [1, 3]) | |
| +def test_histogram_record_10_small_mapping_attrs(benchmark, num_labels): | |
| + def test_histogram_record_10_attrs(): | |
| + hist10.record( | |
| + random.random() * MAX_BOUND_VALUE, | |
| + attributes={f"Key{i}": {"k1": "v1"} for i in range(num_labels)}, | |
| + ) | |
| + | |
| + benchmark(test_histogram_record_10_attrs) | |
| + | |
| + | |
| +@pytest.mark.parametrize("num_labels", [1, 3]) | |
| +def test_histogram_record_10_complex_attrs(benchmark, num_labels): | |
| + def test_histogram_record_10_attrs(): | |
| + hist10.record( | |
| + random.random() * MAX_BOUND_VALUE, | |
| + attributes={f"Key{i}": {"k1": "v1", "k2": {"k3": "v3", "k4": [1, 2, 3]}} for i in range(num_labels)}, | |
| + ) | |
| + | |
| + benchmark(test_histogram_record_10_attrs) | |
| + | |
| + | |
| +@pytest.mark.parametrize("num_labels", [1, 3]) | |
| +def test_histogram_record_10_array_attrs(benchmark, num_labels): | |
| + def test_histogram_record_10_attrs(): | |
| + hist10.record( | |
| + random.random() * MAX_BOUND_VALUE, | |
| + attributes={f"Key{i}": ["k1", "v1", "k2", "k3", "v3", "k4", "1", "2", "3"] for i in range(num_labels)}, | |
| + ) | |
| + | |
| + benchmark(test_histogram_record_10_attrs) | |
| + | |
| + | |
| +@pytest.mark.parametrize("num_labels", [1, 3]) | |
| +def test_histogram_record_10_json_string_attrs(benchmark, num_labels): | |
| + def test_histogram_record_10_attrs(): | |
| + hist10.record( | |
| + random.random() * MAX_BOUND_VALUE, | |
| + attributes={ | |
| + f"Key{i}": json.dumps({"k1": "v1", "k2": {"k3": "v3", "k4": [1, 2, 3]}}) for i in range(num_labels) | |
| + }, | |
| + ) | |
| + | |
| + benchmark(test_histogram_record_10_attrs) | |
| + | |
| + | |
| @pytest.mark.parametrize("num_labels", [0, 1, 3, 5, 7]) | |
| def test_histogram_record_49(benchmark, num_labels): | |
| - labels = {} | |
| - for i in range(num_labels): | |
| - labels[f"Key{i}"] = "Value{i}" | |
| - | |
| def benchmark_histogram_record_49(): | |
| - hist49.record(random.random() * MAX_BOUND_VALUE) | |
| + hist49.record( | |
| + random.random() * MAX_BOUND_VALUE, | |
| + attributes={f"Key{i}": f"Value{i}" for i in range(num_labels)}, | |
| + ) | |
| benchmark(benchmark_histogram_record_49) | |
| @pytest.mark.parametrize("num_labels", [0, 1, 3, 5, 7]) | |
| def test_histogram_record_50(benchmark, num_labels): | |
| - labels = {} | |
| - for i in range(num_labels): | |
| - labels[f"Key{i}"] = "Value{i}" | |
| - | |
| def benchmark_histogram_record_50(): | |
| - hist50.record(random.random() * MAX_BOUND_VALUE) | |
| + hist50.record( | |
| + random.random() * MAX_BOUND_VALUE, | |
| + attributes={f"Key{i}": f"Value{i}" for i in range(num_labels)}, | |
| + ) | |
| benchmark(benchmark_histogram_record_50) | |
| @pytest.mark.parametrize("num_labels", [0, 1, 3, 5, 7]) | |
| def test_histogram_record_1000(benchmark, num_labels): | |
| - labels = {} | |
| - for i in range(num_labels): | |
| - labels[f"Key{i}"] = "Value{i}" | |
| - | |
| def benchmark_histogram_record_1000(): | |
| - hist1000.record(random.random() * MAX_BOUND_VALUE) | |
| + hist1000.record( | |
| + random.random() * MAX_BOUND_VALUE, | |
| + attributes={f"Key{i}": f"Value{i}" for i in range(num_labels)}, | |
| + ) | |
| benchmark(benchmark_histogram_record_1000) | |
| diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py | |
| index 471a94da..300f5c3c 100644 | |
| --- a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py | |
| +++ b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py | |
| import os | |
| import threading | |
| import traceback | |
| import warnings | |
| -from collections.abc import Callable | |
| +from collections.abc import Callable, Mapping, Sequence | |
| from dataclasses import dataclass, field | |
| from os import environ | |
| from threading import Lock | |
| from time import time_ns | |
| +from types import NoneType | |
| from typing import ( # noqa | |
| Any, | |
| + Tuple, | |
| + Union, | |
| cast, | |
| overload, | |
| ) | |
| from opentelemetry._logs import ( | |
| get_logger, | |
| get_logger_provider, | |
| ) | |
| -from opentelemetry.attributes import _VALID_ANY_VALUE_TYPES, BoundedAttributes | |
| +from opentelemetry.attributes import BoundedAttributes | |
| from opentelemetry.context import get_current | |
| from opentelemetry.context.context import Context | |
| from opentelemetry.metrics import MeterProvider, get_meter_provider | |
| from opentelemetry.trace import ( | |
| format_span_id, | |
| format_trace_id, | |
| ) | |
| -from opentelemetry.util.types import AnyValue, _ExtendedAttributes | |
| +from opentelemetry.util.types import AnyValue, Attributes | |
| # pylint: disable=too-many-lines | |
| class LoggingHandler(logging.Handler): | |
| ) | |
| @staticmethod | |
| - def _get_attributes(record: logging.LogRecord) -> _ExtendedAttributes: | |
| + def _get_attributes(record: logging.LogRecord) -> Attributes: | |
| attributes = {k: v for k, v in vars(record).items() if k not in _RESERVED_ATTRS} | |
| # Add standard code attributes for logs. | |
| class LoggingHandler(logging.Handler): | |
| # For more background, see: https://github.com/open-telemetry/opentelemetry-python/pull/4216 | |
| if not record.args and not isinstance(record.msg, str): | |
| # if record.msg is not a value we can export, cast it to string | |
| - if not isinstance(record.msg, _VALID_ANY_VALUE_TYPES): | |
| + # TODO: https://github.com/open-telemetry/opentelemetry-python/issues/5304 - do something better | |
| + # than just casting to a string. | |
| + if not isinstance( | |
| + record.msg, | |
| + ( | |
| + NoneType, | |
| + bool, | |
| + bytes, | |
| + int, | |
| + float, | |
| + str, | |
| + Sequence, | |
| + Mapping, | |
| + ), | |
| + ): | |
| body = str(record.msg) | |
| else: | |
| body = record.msg | |
| class Logger(APILogger): | |
| severity_number: SeverityNumber | None = None, | |
| severity_text: str | None = None, | |
| body: AnyValue | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| event_name: str | None = None, | |
| exception: BaseException | None = None, | |
| ) -> None: | |
| class LoggerProvider(APILoggerProvider): | |
| name: str, | |
| version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> Logger: | |
| scope = InstrumentationScope(name, version, schema_url, attributes) | |
| class LoggerProvider(APILoggerProvider): | |
| name: str, | |
| version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> APILogger: | |
| if self._disabled: | |
| return NoOpLogger( | |
| diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/_exceptions.py b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/_exceptions.py | |
| index 4dd4c7ee..bd4a9538 100644 | |
| --- a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/_exceptions.py | |
| +++ b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/_exceptions.py | |
| import traceback | |
| from opentelemetry._logs import LogRecord | |
| from opentelemetry.attributes import BoundedAttributes | |
| from opentelemetry.semconv.attributes import exception_attributes | |
| -from opentelemetry.util.types import AnyValue, _ExtendedAttributes | |
| +from opentelemetry.util.types import AnyValue, Attributes | |
| def _get_exception_attributes( | |
| def _get_exception_attributes( | |
| def _get_attributes_with_exception( | |
| - attributes: _ExtendedAttributes | None, | |
| + attributes: Attributes, | |
| exception: BaseException | None, | |
| -) -> _ExtendedAttributes | None: | |
| +) -> Attributes: | |
| if exception is None: | |
| return attributes | |
| exception_attributes_map = _get_exception_attributes(exception) | |
| if attributes is None: | |
| - attributes_map: _ExtendedAttributes = {} | |
| + attributes_map: Attributes = {} | |
| else: | |
| attributes_map = attributes | |
| def _get_attributes_with_exception( | |
| attributes=bounded_attributes, | |
| immutable=False, | |
| max_value_len=bounded_attributes.max_value_len, | |
| - extended_attributes=bounded_attributes._extended_attributes, # pylint: disable=protected-access | |
| ) | |
| merged.dropped = bounded_attributes.dropped | |
| for key, value in exception_attributes_map.items(): | |
| def _get_attributes_with_exception( | |
| def _copy_log_record( | |
| record: LogRecord, | |
| - attributes: _ExtendedAttributes | None, | |
| + attributes: Attributes, | |
| ) -> LogRecord: | |
| copied_record = LogRecord( | |
| timestamp=record.timestamp, | |
| def _create_log_record_with_exception( | |
| severity_number=None, | |
| severity_text: str | None = None, | |
| body: AnyValue | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| event_name: str | None = None, | |
| exception: BaseException | None = None, | |
| ) -> LogRecord: | |
| diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/environment_variables/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/environment_variables/__init__.py | |
| index 6f68ad96..303f6292 100644 | |
| --- a/opentelemetry-sdk/src/opentelemetry/sdk/environment_variables/__init__.py | |
| +++ b/opentelemetry-sdk/src/opentelemetry/sdk/environment_variables/__init__.py | |
| OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT = "OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT" | |
| """ | |
| .. envvar:: OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT | |
| -The :envvar:`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` represents the maximum allowed attribute length. | |
| +The :envvar:`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` represents the maximum allowed attribute value length for string attribute values. | |
| """ | |
| OTEL_EVENT_ATTRIBUTE_COUNT_LIMIT = "OTEL_EVENT_ATTRIBUTE_COUNT_LIMIT" | |
| OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = "OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT | |
| """ | |
| .. envvar:: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT | |
| -The :envvar:`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT` represents the maximum allowed length | |
| -span attribute values can have. This takes precedence over :envvar:`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`. | |
| +The :envvar:`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT` represents the maximum allowed attribute value length for string span attribute values. This takes precedence over :envvar:`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`. | |
| """ | |
| OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT = "OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT" | |
| diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py | |
| index 016885bb..8072b6b2 100644 | |
| --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py | |
| +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py | |
| class MeterProvider(APIMeterProvider): | |
| name: str, | |
| version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> APIMeter: | |
| if self._disabled: | |
| return NoOpMeter(name, version=version, schema_url=schema_url) | |
| diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/_view_instrument_match.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/_view_instrument_match.py | |
| index 8abd9d51..43240429 100644 | |
| --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/_view_instrument_match.py | |
| +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/_view_instrument_match.py | |
| # Copyright The OpenTelemetry Authors | |
| # SPDX-License-Identifier: Apache-2.0 | |
| - | |
| -from collections.abc import Sequence | |
| +from collections.abc import Mapping, Sequence | |
| from logging import getLogger | |
| from threading import Lock | |
| from time import time_ns | |
| -from typing import cast | |
| +from types import NoneType | |
| +from typing import TYPE_CHECKING, cast | |
| + | |
| +from typing_extensions import assert_never | |
| from opentelemetry.sdk.metrics._internal.aggregation import ( | |
| Aggregation, | |
| from opentelemetry.sdk.metrics._internal.instrument import _Instrument | |
| from opentelemetry.sdk.metrics._internal.measurement import Measurement | |
| from opentelemetry.sdk.metrics._internal.point import DataPointT | |
| from opentelemetry.sdk.metrics._internal.view import View | |
| +from opentelemetry.util.types import AnyValue, Attributes | |
| _logger = getLogger(__name__) | |
| +_HashedAttributes = str | bool | int | float | bytes | None | tuple["_HashedAttributes", ...] | |
| + | |
| + | |
| +# pylint: disable=inconsistent-return-statements | |
| +def _hash_attributes(value: Attributes | AnyValue) -> _HashedAttributes: | |
| + # Attributes have been cleaned and validated when Measurement was instantiated, | |
| + # so value is guaranteed to match one of the branches below at runtime. | |
| + if isinstance(value, (NoneType, str, int, float, bool, bytes)): | |
| + return value | |
| + if isinstance(value, Sequence): | |
| + return tuple(_hash_attributes(v) for v in value) | |
| + if isinstance(value, Mapping): | |
| + return tuple( | |
| + (k, _hash_attributes(value[k])) | |
| + for k in sorted( | |
| + value, | |
| + key=lambda item: item if isinstance(item, str) else str(item), | |
| + ) | |
| + ) | |
| + if TYPE_CHECKING: | |
| + assert_never(value) | |
| + | |
| class _ViewInstrumentMatch: | |
| def __init__( | |
| class _ViewInstrumentMatch: | |
| ): | |
| self._view = view | |
| self._instrument = instrument | |
| - self._attributes_aggregation: dict[frozenset, _Aggregation] = {} | |
| + self._attributes_aggregation: dict[_HashedAttributes, _Aggregation] = {} | |
| self._lock = Lock() | |
| self._instrument_class_aggregation = instrument_class_aggregation | |
| self._name = self._view._name or self._instrument.name | |
| class _ViewInstrumentMatch: | |
| # pylint: disable=protected-access | |
| def consume_measurement(self, measurement: Measurement, should_sample_exemplar: bool = True) -> None: | |
| - if self._view._attribute_keys is not None: | |
| - attributes = {} | |
| - | |
| - for key, value in (measurement.attributes or {}).items(): | |
| - if key in self._view._attribute_keys: | |
| - attributes[key] = value | |
| - elif measurement.attributes is not None: | |
| + attributes = {} | |
| + if measurement.attributes: | |
| + # Make a shallow copy since the user can mutate the dict after the fact. | |
| + # The user can still modify mutable attribute values (lists/dicts) | |
| + # leading to unexpected behavior, but deep copying is expensive. | |
| attributes = dict(measurement.attributes) | |
| - else: | |
| - attributes = {} | |
| + if self._view._attribute_keys is not None: | |
| + attributes = {k: v for k, v in attributes.items() if k in self._view._attribute_keys} | |
| - aggr_key = frozenset(attributes.items()) | |
| + aggr_key = _hash_attributes(attributes) | |
| if aggr_key not in self._attributes_aggregation: | |
| with self._lock: | |
| diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py | |
| index c3ee9c47..d941569b 100644 | |
| --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py | |
| +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py | |
| from opentelemetry.metrics._internal.instrument import ( | |
| _MetricsHistogramAdvisory, | |
| ) | |
| from opentelemetry.sdk.metrics._internal.measurement import Measurement | |
| +from opentelemetry.util.types import Attributes | |
| if TYPE_CHECKING: | |
| from opentelemetry.sdk.metrics._internal import ( | |
| class Counter(_Synchronous, APICounter): | |
| def add( | |
| self, | |
| amount: int | float, | |
| - attributes: dict[str, str] | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ): | |
| if not self._is_enabled(): | |
| class UpDownCounter(_Synchronous, APIUpDownCounter): | |
| def add( | |
| self, | |
| amount: int | float, | |
| - attributes: dict[str, str] | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ): | |
| if not self._is_enabled(): | |
| class Histogram(_Synchronous, APIHistogram): | |
| def record( | |
| self, | |
| amount: int | float, | |
| - attributes: dict[str, str] | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ): | |
| if not self._is_enabled(): | |
| class Gauge(_Synchronous, APIGauge): | |
| def set( | |
| self, | |
| amount: int | float, | |
| - attributes: dict[str, str] | None = None, | |
| + attributes: Attributes = None, | |
| context: Context | None = None, | |
| ): | |
| if not self._is_enabled(): | |
| diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/measurement.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/measurement.py | |
| index cd81c39f..4e9d5eea 100644 | |
| --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/measurement.py | |
| +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/measurement.py | |
| from __future__ import annotations | |
| +from collections.abc import Mapping | |
| from dataclasses import dataclass | |
| +from logging import getLogger | |
| from typing import TYPE_CHECKING | |
| +from opentelemetry.attributes import _clean_attribute_value | |
| from opentelemetry.context import Context | |
| from opentelemetry.util.types import Attributes | |
| +_logger = getLogger(__name__) | |
| + | |
| if TYPE_CHECKING: | |
| from opentelemetry.sdk.metrics._internal.instrument import _Instrument | |
| class Measurement: | |
| time_unix_nano: The time the API call was made to record the Measurement | |
| instrument: The instrument that produced this `Measurement`. | |
| context: The active Context of the Measurement at API call time. | |
| - attributes: Measurement attributes | |
| + attributes: Measurement attributes. Mutating mutable attribute values (lists or dicts) | |
| + outside of the Measurement object can lead to undefined and bad behavior. | |
| """ | |
| value: int | float | |
| class Measurement: | |
| instrument: _Instrument | |
| context: Context | |
| attributes: Attributes = None | |
| + | |
| + def __post_init__(self) -> None: | |
| + if self.attributes is not None: | |
| + if isinstance(self.attributes, Mapping): | |
| + object.__setattr__( | |
| + self, | |
| + "attributes", | |
| + _clean_attribute_value(self.attributes, None), | |
| + ) | |
| + else: | |
| + _logger.warning( | |
| + "Invalid type '%s' for attributes. Expected a Mapping or None.", | |
| + type(self.attributes), | |
| + ) | |
| + object.__setattr__(self, "attributes", None) | |
| diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py | |
| index a84c9f25..36aa826c 100644 | |
| --- a/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py | |
| +++ b/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py | |
| from opentelemetry.sdk.version import ( | |
| __version__ as _OPENTELEMETRY_SDK_VERSION, | |
| ) | |
| from opentelemetry.semconv.resource import ResourceAttributes | |
| -from opentelemetry.util.types import AttributeValue | |
| +from opentelemetry.util.types import AnyValue | |
| psutil: ModuleType | None = None | |
| try: | |
| except ImportError: | |
| pass | |
| -LabelValue = AttributeValue | |
| +LabelValue = AnyValue | |
| Attributes = Mapping[str, LabelValue] | |
| logger = logging.getLogger(__name__) | |
| - | |
| CLOUD_PROVIDER = ResourceAttributes.CLOUD_PROVIDER | |
| CLOUD_ACCOUNT_ID = ResourceAttributes.CLOUD_ACCOUNT_ID | |
| CLOUD_REGION = ResourceAttributes.CLOUD_REGION | |
| class Resource: | |
| _schema_url: str | |
| def __init__(self, attributes: Attributes, schema_url: str | None = None): | |
| - self._attributes = BoundedAttributes(attributes=attributes) | |
| + # Immutable set to true so attributes cannot be added or removed after creation. | |
| + self._attributes = BoundedAttributes(attributes=attributes, immutable=True) | |
| if schema_url is None: | |
| schema_url = "" | |
| self._schema_url = schema_url | |
| class OTELResourceDetector(ResourceDetector): | |
| # pylint: disable=no-self-use | |
| def detect(self) -> "Resource": | |
| env_resources_items = environ.get(OTEL_RESOURCE_ATTRIBUTES) | |
| - env_resource_map: dict[str, AttributeValue] = {} | |
| + env_resource_map: dict[str, AnyValue] = {} | |
| if env_resources_items: | |
| for item in env_resources_items.split(","): | |
| class ProcessResourceDetector(ResourceDetector): | |
| # default because full command arguments are opt-in. | |
| _process_command = sys.orig_argv[0] if sys.orig_argv else "" | |
| executable = sys.executable or "" | |
| - resource_info: dict[str, AttributeValue] = { | |
| + resource_info: dict[str, AnyValue] = { | |
| PROCESS_RUNTIME_DESCRIPTION: sys.version, | |
| PROCESS_RUNTIME_NAME: sys.implementation.name, | |
| PROCESS_RUNTIME_VERSION: _runtime_version, | |
| diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py | |
| index 53994894..14d6573d 100644 | |
| --- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py | |
| +++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py | |
| class Span(trace_api.Span, ReadableSpan): | |
| self._events = self._new_events() | |
| if events: | |
| for event in events: | |
| + # Immutable set to true so attributes cannot be added or removed after creation. | |
| event._attributes = BoundedAttributes( | |
| self._limits.max_event_attributes, | |
| event.attributes, | |
| max_value_len=self._limits.max_attribute_length, | |
| + immutable=True, | |
| ) | |
| self._events.append(event) | |
| class Span(trace_api.Span, ReadableSpan): | |
| valid_links = [] | |
| for link in links: | |
| if link and _is_valid_link(link.context, link.attributes): | |
| + # Immutable set to true so attributes cannot be added or removed after creation. | |
| # pylint: disable=protected-access | |
| link._attributes = BoundedAttributes( | |
| self._limits.max_link_attributes, | |
| link.attributes, | |
| max_value_len=self._limits.max_attribute_length, | |
| + immutable=True, | |
| ) | |
| valid_links.append(link) | |
| class Span(trace_api.Span, ReadableSpan): | |
| def get_span_context(self) -> trace_api.SpanContext: | |
| return typing.cast(trace_api.SpanContext, self._context) | |
| - def set_attributes(self, attributes: Mapping[str, types.AttributeValue]) -> None: | |
| + def set_attributes(self, attributes: Mapping[str, types.AnyValue]) -> None: | |
| with self._lock: | |
| if self._end_time is not None: | |
| logger.warning("Setting attribute on ended span.") | |
| class Span(trace_api.Span, ReadableSpan): | |
| self._attributes._set_items(attributes) # pylint: disable=protected-access | |
| - def set_attribute(self, key: str, value: types.AttributeValue) -> None: | |
| + def set_attribute(self, key: str, value: types.AnyValue) -> None: | |
| with self._lock: | |
| if self._end_time is not None: | |
| logger.warning("Setting attribute on ended span.") | |
| class Span(trace_api.Span, ReadableSpan): | |
| attributes: types.Attributes = None, | |
| timestamp: int | None = None, | |
| ) -> None: | |
| + # Immutable set to true so attributes cannot be added or removed after creation. | |
| attributes = BoundedAttributes( | |
| self._limits.max_event_attributes, | |
| attributes, | |
| max_value_len=self._limits.max_attribute_length, | |
| + immutable=True, | |
| ) | |
| self._add_event( | |
| Event( | |
| class Span(trace_api.Span, ReadableSpan): | |
| ) -> None: | |
| if not _is_valid_link(context, attributes): | |
| return | |
| - | |
| + # Immutable set to true so attributes cannot be added or removed after creation. | |
| attributes = BoundedAttributes( | |
| self._limits.max_link_attributes, | |
| attributes, | |
| max_value_len=self._limits.max_attribute_length, | |
| + immutable=True, | |
| ) | |
| self._add_link( | |
| trace_api.Link( | |
| class Span(trace_api.Span, ReadableSpan): | |
| module = type(exception).__module__ | |
| qualname = type(exception).__qualname__ | |
| exception_type = f"{module}.{qualname}" if module and module != "builtins" else qualname | |
| - _attributes: MutableMapping[str, types.AttributeValue] = { | |
| + _attributes: MutableMapping[str, types.AnyValue] = { | |
| EXCEPTION_TYPE: exception_type, | |
| EXCEPTION_MESSAGE: str(exception), | |
| EXCEPTION_STACKTRACE: stacktrace, | |
| class TracerProvider(trace_api.TracerProvider): | |
| instrumenting_module_name: str, | |
| instrumenting_library_version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: types.Attributes | None = None, | |
| + attributes: types.Attributes = None, | |
| ) -> "trace_api.Tracer": | |
| if self._disabled: | |
| return NoOpTracer() | |
| diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/trace/_sampling_experimental/_sampler.py b/opentelemetry-sdk/src/opentelemetry/sdk/trace/_sampling_experimental/_sampler.py | |
| index b15dcfb0..7d74a3fb 100644 | |
| --- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/_sampling_experimental/_sampler.py | |
| +++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/_sampling_experimental/_sampler.py | |
| class _CompositeSampler(Sampler): | |
| trace_id: int, | |
| name: str, | |
| kind: SpanKind | None = None, | |
| - attributes: Attributes | None = None, | |
| + attributes: Attributes = None, | |
| links: Sequence[Link] | None = None, | |
| trace_state: TraceState | None = None, | |
| ) -> SamplingResult: | |
| diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.pyi b/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.pyi | |
| index d2add7c7..1b769659 100644 | |
| --- a/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.pyi | |
| +++ b/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.pyi | |
| from typing import ( | |
| overload, | |
| ) | |
| -from opentelemetry.util.types import AttributesAsKey, AttributeValue | |
| +from opentelemetry.util.types import AnyValue, AttributesAsKey | |
| _T = TypeVar("_T") | |
| _KT = TypeVar("_KT") | |
| _VT = TypeVar("_VT") | |
| def ns_to_iso_str(nanoseconds: int) -> str: ... | |
| def get_dict_as_key( | |
| - labels: Mapping[str, AttributeValue], | |
| + labels: Mapping[str, AnyValue], | |
| ) -> AttributesAsKey: ... | |
| # pylint: disable=no-self-use | |
| diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/util/instrumentation.py b/opentelemetry-sdk/src/opentelemetry/sdk/util/instrumentation.py | |
| index 3f999d80..710bd81d 100644 | |
| --- a/opentelemetry-sdk/src/opentelemetry/sdk/util/instrumentation.py | |
| +++ b/opentelemetry-sdk/src/opentelemetry/sdk/util/instrumentation.py | |
| from opentelemetry.attributes import BoundedAttributes | |
| from opentelemetry.util.types import ( # TODO: see if we can remove F401 when using new sphinx version # noqa: F401 # pylint: disable=unused-import | |
| AnyValue, | |
| Attributes, | |
| - _ExtendedAttributes, | |
| ) | |
| class InstrumentationScope: | |
| name: str, | |
| version: str | None = None, | |
| schema_url: str | None = None, | |
| - attributes: _ExtendedAttributes | None = None, | |
| + attributes: Attributes = None, | |
| ) -> None: | |
| self._name = name | |
| self._version = version | |
| if schema_url is None: | |
| schema_url = "" | |
| self._schema_url = schema_url | |
| - self._attributes = BoundedAttributes(attributes=attributes) | |
| + # Attributes cannot be added/removed after creation. | |
| + self._attributes = BoundedAttributes(attributes=attributes, immutable=True) | |
| def __repr__(self) -> str: | |
| return f"{type(self).__name__}({self._name}, {self._version}, {self._schema_url}, {self._attributes})" | |
| diff --git a/opentelemetry-sdk/tests/logs/test_logs.py b/opentelemetry-sdk/tests/logs/test_logs.py | |
| index 47fa09e2..171a680b 100644 | |
| --- a/opentelemetry-sdk/tests/logs/test_logs.py | |
| +++ b/opentelemetry-sdk/tests/logs/test_logs.py | |
| class TestLogger(unittest.TestCase): | |
| original_attributes = BoundedAttributes( | |
| attributes={"custom": "value"}, | |
| immutable=True, | |
| - extended_attributes=True, | |
| ) | |
| log_record = LogRecord( | |
| observed_timestamp=0, | |
| diff --git a/opentelemetry-sdk/tests/metrics/test_metrics.py b/opentelemetry-sdk/tests/metrics/test_metrics.py | |
| index b84088a5..d093873e 100644 | |
| --- a/opentelemetry-sdk/tests/metrics/test_metrics.py | |
| +++ b/opentelemetry-sdk/tests/metrics/test_metrics.py | |
| from opentelemetry.sdk.metrics._internal import ( | |
| _ProxyMeterConfig, | |
| _RuleBasedMeterConfigurator, | |
| ) | |
| +from opentelemetry.sdk.metrics._internal.measurement import Measurement | |
| from opentelemetry.sdk.metrics.export import ( | |
| InMemoryMetricReader, | |
| Metric, | |
| class TestDuplicateInstrumentAggregateData(TestCase): | |
| self.assertEqual(metric_1.unit, "unit") | |
| self.assertEqual(metric_1.description, "description") | |
| self.assertEqual(next(iter(metric_1.data.data_points)).value, 7) | |
| + | |
| + | |
| +class TestMeasurement(TestCase): | |
| + def test_measurement_attributes_cleaned(self): | |
| + measurement = Measurement( | |
| + value=10, | |
| + time_unix_nano=0, | |
| + instrument=Mock(), | |
| + context=Mock(), | |
| + attributes={"a": "b", 1: 2, "seq": [1, 2]}, | |
| + ) | |
| + self.assertEqual( | |
| + measurement.attributes, | |
| + {"a": "b", "1": 2, "seq": (1, 2)}, | |
| + ) | |
| + | |
| + def test_measurement_attributes_invalid_type(self): | |
| + with self.assertLogs(level=WARNING) as logs: | |
| + measurement = Measurement( | |
| + value=10, | |
| + time_unix_nano=0, | |
| + instrument=Mock(), | |
| + context=Mock(), | |
| + attributes="invalid", | |
| + ) | |
| + self.assertIsNone(measurement.attributes) | |
| + self.assertIn("Invalid type", logs.output[0]) | |
| + | |
| + def test_measurement_attributes_none_or_empty(self): | |
| + m1 = Measurement( | |
| + value=10, | |
| + time_unix_nano=0, | |
| + instrument=Mock(), | |
| + context=Mock(), | |
| + attributes=None, | |
| + ) | |
| + self.assertIsNone(m1.attributes) | |
| + | |
| + m2 = Measurement( | |
| + value=10, | |
| + time_unix_nano=0, | |
| + instrument=Mock(), | |
| + context=Mock(), | |
| + attributes={}, | |
| + ) | |
| + self.assertEqual(m2.attributes, {}) | |
| diff --git a/opentelemetry-sdk/tests/metrics/test_view_instrument_match.py b/opentelemetry-sdk/tests/metrics/test_view_instrument_match.py | |
| index 6ea757c1..8985a339 100644 | |
| --- a/opentelemetry-sdk/tests/metrics/test_view_instrument_match.py | |
| +++ b/opentelemetry-sdk/tests/metrics/test_view_instrument_match.py | |
| from unittest.mock import MagicMock, Mock, patch | |
| from opentelemetry.context import Context | |
| from opentelemetry.sdk.metrics._internal._view_instrument_match import ( | |
| + _hash_attributes, | |
| _ViewInstrumentMatch, | |
| ) | |
| from opentelemetry.sdk.metrics._internal.aggregation import ( | |
| class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name | |
| ) | |
| self.assertEqual( | |
| view_instrument_match._attributes_aggregation, | |
| - {frozenset([("c", "d")]): self.mock_created_aggregation}, | |
| + {_hash_attributes({"c": "d"}): self.mock_created_aggregation}, | |
| ) | |
| view_instrument_match.consume_measurement( | |
| class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name | |
| self.assertEqual( | |
| view_instrument_match._attributes_aggregation, | |
| { | |
| - frozenset(): self.mock_created_aggregation, | |
| - frozenset([("c", "d")]): self.mock_created_aggregation, | |
| + _hash_attributes({}): self.mock_created_aggregation, | |
| + _hash_attributes({"c": "d"}): self.mock_created_aggregation, | |
| }, | |
| ) | |
| - # None attribute_keys (default) will keep all attributes | |
| + # setup new instrument match without `attribute_keys` set, defaults to keeping | |
| + # all attributes. | |
| view_instrument_match = _ViewInstrumentMatch( | |
| view=View( | |
| instrument_name="instrument1", | |
| class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name | |
| ) | |
| self.assertEqual( | |
| view_instrument_match._attributes_aggregation, | |
| - {frozenset([("c", "d"), ("f", "g")]): self.mock_created_aggregation}, | |
| + {_hash_attributes({"c": "d", "f": "g"}): self.mock_created_aggregation}, | |
| ) | |
| - # empty set attribute_keys will drop all labels and aggregate | |
| + # empty set attribute_keys will drop all attributes and aggregate | |
| # everything together | |
| view_instrument_match = _ViewInstrumentMatch( | |
| view=View( | |
| class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name | |
| time_unix_nano=time_ns(), | |
| instrument=instrument1, | |
| context=Context(), | |
| - attributes=None, | |
| + attributes={"a": 1, "b": 2}, | |
| ) | |
| ) | |
| self.assertEqual( | |
| view_instrument_match._attributes_aggregation, | |
| - {frozenset({}): self.mock_created_aggregation}, | |
| + {_hash_attributes({}): self.mock_created_aggregation}, | |
| ) | |
| # Test that a drop aggregation is handled in the same way as any | |
| class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name | |
| ) | |
| ) | |
| self.assertIsInstance( | |
| - view_instrument_match._attributes_aggregation[frozenset({})], | |
| + view_instrument_match._attributes_aggregation[_hash_attributes({})], | |
| _DropAggregation, | |
| ) | |
| class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name | |
| def test_consume_measurement_attributes_are_copied(self): | |
| """Mutating the attributes dict after recording must not affect stored data points.""" | |
| + # Note mutating mutable objects in the attributes dict will still cause issues, | |
| + # as they are not deep copied. | |
| instrument1 = _Counter( | |
| "instrument1", | |
| Mock(), | |
| class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name | |
| # Mutate the original dict after recording | |
| attributes["key"] = "mutated" | |
| - | |
| number_data_points = view_instrument_match.collect(AggregationTemporality.CUMULATIVE, 0) | |
| number_data_points = list(number_data_points) | |
| self.assertEqual(len(number_data_points), 1) | |
| - self.assertEqual(number_data_points[0].attributes, {"key": "original"}) | |
| + self.assertEqual( | |
| + number_data_points[0].attributes, | |
| + {"key": "original"}, | |
| + ) | |
| @patch( | |
| "opentelemetry.sdk.metrics._internal._view_instrument_match.time_ns", | |
| class Test_ViewInstrumentMatch(TestCase): # pylint: disable=invalid-name | |
| ) | |
| self.assertIsInstance( | |
| - view_instrument_match._attributes_aggregation[frozenset({("c", "d")})], | |
| + view_instrument_match._attributes_aggregation[_hash_attributes({"c": "d"})], | |
| _LastValueAggregation, | |
| ) | |
| + def test_hash_attributes_works_as_stable_hash_key(self): | |
| + attributes = { | |
| + "a": [1, 2], | |
| + "b": [2, 1], | |
| + "c": b"1234asf", | |
| + "d": 1.2324124, | |
| + "e": -2.32323124, | |
| + "f": {1: 2, 2: (1, 2, 3), 3: "a", 4: "bc"}, | |
| + } | |
| + self.assertEqual( | |
| + _hash_attributes(attributes), | |
| + _hash_attributes(attributes), | |
| + ) | |
| + | |
| + self.assertNotEqual( | |
| + _hash_attributes({"1": (1, "2", 3, "4")}), | |
| + _hash_attributes({"1": ("1", 2, "3", 4)}), | |
| + ) | |
| + | |
| + def test_hash_attributes_stable_hash_key_order_independence(self): | |
| + attrs1 = {"b": 2, "a": 1, "c": 3} | |
| + attrs2 = {"a": 1, "c": 3, "b": 2} | |
| + self.assertEqual( | |
| + _hash_attributes(attrs1), | |
| + _hash_attributes(attrs2), | |
| + ) | |
| + | |
| + nested1 = {"root": {"z": (3, 2, 1), "x": "val", "y": b"bytes_data"}} | |
| + nested2 = {"root": {"y": b"bytes_data", "z": (3, 2, 1), "x": "val"}} | |
| + self.assertEqual( | |
| + _hash_attributes(nested1), | |
| + _hash_attributes(nested2), | |
| + ) | |
| + | |
| + def test_hash_attributes_stable_hash_with_tuples_and_nested_dicts(self): | |
| + complex_attrs_a = { | |
| + "service": {"name": "test-svc", "version": "1.0"}, | |
| + "tags": ("prod", "us-east-1"), | |
| + "endpoints": ( | |
| + {"host": "a.com", "port": 80}, | |
| + {"host": "b.com", "port": 443}, | |
| + ), | |
| + "payload": b"binary-content", | |
| + } | |
| + complex_attrs_b = { | |
| + "payload": b"binary-content", | |
| + "endpoints": ( | |
| + {"port": 80, "host": "a.com"}, | |
| + {"port": 443, "host": "b.com"}, | |
| + ), | |
| + "service": {"version": "1.0", "name": "test-svc"}, | |
| + "tags": ("prod", "us-east-1"), | |
| + } | |
| + self.assertEqual( | |
| + _hash_attributes(complex_attrs_a), | |
| + _hash_attributes(complex_attrs_b), | |
| + ) | |
| + | |
| + def test_hash_attributes_tuple_and_list_equivalence(self): | |
| + attrs_tuple = {"values": (1, 2, 3), "nested": {"items": ("a", "b")}} | |
| + attrs_list = {"values": [1, 2, 3], "nested": {"items": ["a", "b"]}} | |
| + self.assertEqual( | |
| + _hash_attributes(attrs_tuple), | |
| + _hash_attributes(attrs_list), | |
| + ) | |
| + | |
| + def test_consume_measurement_with_non_string_keys(self): | |
| + instrument1 = _Counter( | |
| + name="instrument1", | |
| + instrumentation_scope=Mock(), | |
| + measurement_consumer=Mock(), | |
| + description="description", | |
| + unit="unit", | |
| + ) | |
| + instrument1.instrumentation_scope = self.mock_instrumentation_scope | |
| + view_instrument_match = _ViewInstrumentMatch( | |
| + view=View( | |
| + instrument_name="instrument1", | |
| + name="name", | |
| + aggregation=DefaultAggregation(), | |
| + ), | |
| + instrument=instrument1, | |
| + instrument_class_aggregation={_Counter: LastValueAggregation()}, | |
| + ) | |
| + | |
| + attributes = {"c": 1, 22: 3, (1,): 2} | |
| + | |
| + measurement = Measurement( | |
| + value=0, | |
| + time_unix_nano=time_ns(), | |
| + instrument=Mock(name="instrument1"), | |
| + context=Context(), | |
| + attributes=attributes, | |
| + ) | |
| + view_instrument_match.consume_measurement(measurement) | |
| + self.assertEqual( | |
| + measurement.attributes, | |
| + {"c": 1, "22": 3, "(1,)": 2}, | |
| + ) | |
| + self.assertIn( | |
| + _hash_attributes(measurement.attributes), | |
| + view_instrument_match._attributes_aggregation, | |
| + ) | |
| + | |
| + def test_consume_measurement_stable_hash_key_order(self): | |
| + instrument1 = _Counter( | |
| + "instrument1", | |
| + Mock(), | |
| + Mock(), | |
| + description="description", | |
| + unit="unit", | |
| + ) | |
| + instrument1.instrumentation_scope = self.mock_instrumentation_scope | |
| + view_instrument_match = _ViewInstrumentMatch( | |
| + view=View( | |
| + instrument_name="instrument1", | |
| + name="name", | |
| + aggregation=DefaultAggregation(), | |
| + ), | |
| + instrument=instrument1, | |
| + instrument_class_aggregation=MagicMock(**{"__getitem__.return_value": DefaultAggregation()}), | |
| + ) | |
| + | |
| + attrs1 = { | |
| + "service": {"version": "1.0", "name": "app"}, | |
| + "tags": ("prod", "v1"), | |
| + "region": "us-east-1", | |
| + } | |
| + attrs2 = { | |
| + "region": "us-east-1", | |
| + "tags": ("prod", "v1"), | |
| + "service": {"name": "app", "version": "1.0"}, | |
| + } | |
| + view_instrument_match.consume_measurement( | |
| + Measurement( | |
| + value=1, | |
| + time_unix_nano=time_ns(), | |
| + instrument=instrument1, | |
| + context=Context(), | |
| + attributes=attrs1, | |
| + ) | |
| + ) | |
| + view_instrument_match.consume_measurement( | |
| + Measurement( | |
| + value=2, | |
| + time_unix_nano=time_ns(), | |
| + instrument=instrument1, | |
| + context=Context(), | |
| + attributes=attrs2, | |
| + ) | |
| + ) | |
| + | |
| + self.assertEqual(len(view_instrument_match._attributes_aggregation), 1) | |
| + expected_key = _hash_attributes(attrs1) | |
| + self.assertIn(expected_key, view_instrument_match._attributes_aggregation) | |
| + | |
| class TestSimpleFixedSizeExemplarReservoir(TestCase): | |
| def test_consume_measurement_with_custom_reservoir_factory(self): | |
| diff --git a/opentelemetry-sdk/tests/resources/test_resources.py b/opentelemetry-sdk/tests/resources/test_resources.py | |
| index 282611dd..973b9685 100644 | |
| --- a/opentelemetry-sdk/tests/resources/test_resources.py | |
| +++ b/opentelemetry-sdk/tests/resources/test_resources.py | |
| class TestResources(unittest.TestCase): | |
| ) | |
| def test_invalid_resource_attribute_values(self): | |
| + # This class has no __str__ or __repr__ method, so BoundedAttributes does | |
| + # not attempt to convert it to a string and defaults to returning None. | |
| + class NoStrNoRepr: | |
| + def __init__(self): | |
| + pass | |
| + | |
| + # Empty key will get dropped. | |
| with self.assertLogs(level=WARNING): | |
| resource = Resource( | |
| { | |
| SERVICE_NAME: "test", | |
| - "non-primitive-data-type": {}, | |
| - "invalid-byte-type-attribute": (b"\xd8\xe1\xb7\xeb\xa8\xe5 \xd2\xb7\xe1"), | |
| + "bad-type": NoStrNoRepr(), | |
| "": "empty-key-value", | |
| - None: "null-key-value", | |
| - "another-non-primitive": uuid.uuid4(), | |
| } | |
| ) | |
| self.assertEqual( | |
| resource.attributes, | |
| { | |
| SERVICE_NAME: "test", | |
| + "bad-type": None, | |
| }, | |
| ) | |
| - self.assertEqual(len(resource.attributes), 1) | |
| + self.assertEqual(len(resource.attributes), 2) | |
| def test_aggregated_resources_no_detectors(self): | |
| aggregated_resources = get_aggregated_resources([]) | |
| diff --git a/opentelemetry-sdk/tests/trace/test_trace.py b/opentelemetry-sdk/tests/trace/test_trace.py | |
| index c139e44e..81728a08 100644 | |
| --- a/opentelemetry-sdk/tests/trace/test_trace.py | |
| +++ b/opentelemetry-sdk/tests/trace/test_trace.py | |
| class TestSpan(unittest.TestCase): | |
| root.set_attribute("http.response.status_code", 200) | |
| root.set_attribute("http.status_text", "OK") | |
| root.set_attribute("misc.pi", 3.14) | |
| - | |
| + root.set_attribute("mapping-key", {"key": "value"}) | |
| + root.set_attribute("array-key", [1, 2, 3]) | |
| + root.set_attribute( | |
| + "complex-key", | |
| + [{"key1": "value1"}, {"key2": 42}, "key3", [1, 2, 3]], | |
| + ) | |
| # Setting an attribute with the same key as an existing attribute | |
| # SHOULD overwrite the existing attribute's value. | |
| root.set_attribute("attr-key", "attr-value1") | |
| class TestSpan(unittest.TestCase): | |
| list_of_numerics = [123, 314, 0] | |
| root.set_attribute("list-of-numerics", list_of_numerics) | |
| - self.assertEqual(len(root.attributes), 9) | |
| + self.assertEqual(len(root.attributes), 12) | |
| self.assertEqual(root.attributes["http.request.method"], "GET") | |
| self.assertEqual( | |
| root.attributes["url.full"], | |
| class TestSpan(unittest.TestCase): | |
| self.assertEqual(root.attributes["attr-in-both"], "span-attr") | |
| def test_invalid_attribute_values(self): | |
| - with self.tracer.start_as_current_span("root") as root: | |
| - with self.assertLogs(level=WARNING): | |
| - root.set_attributes({"correct-value": "foo", "non-primitive-data-type": {}}) | |
| + # This class has no __str__ or __repr__ method, so BoundedAttributes does | |
| + # not attempt to convert it to a string and defaults to returning None. | |
| + class NoStrNoRepr: | |
| + def __init__(self): | |
| + pass | |
| + with self.tracer.start_as_current_span("root") as root: | |
| with self.assertLogs(level=WARNING): | |
| - root.set_attribute("non-primitive-data-type", {}) | |
| - with self.assertLogs(level=WARNING): | |
| - root.set_attribute( | |
| - "list-of-mixed-data-types-numeric-first", | |
| - [123, False, "string"], | |
| - ) | |
| - with self.assertLogs(level=WARNING): | |
| - root.set_attribute( | |
| - "list-of-mixed-data-types-non-numeric-first", | |
| - [False, 123, "string"], | |
| + root.set_attributes( | |
| + { | |
| + "correct-value": "foo", | |
| + "bad-type": NoStrNoRepr(), | |
| + } | |
| ) | |
| - with self.assertLogs(level=WARNING): | |
| - root.set_attribute("list-with-non-primitive-data-type", [{}, 123]) | |
| - with self.assertLogs(level=WARNING): | |
| - root.set_attribute("list-with-numeric-and-bool", [1, True]) | |
| - with self.assertLogs(level=WARNING): | |
| - root.set_attribute("", 123) | |
| - with self.assertLogs(level=WARNING): | |
| - root.set_attribute(None, 123) | |
| - | |
| - self.assertEqual(len(root.attributes), 1) | |
| + self.assertEqual(len(root.attributes), 2) | |
| self.assertEqual(root.attributes["correct-value"], "foo") | |
| + self.assertIsNone(root.attributes["bad-type"]) | |
| def test_byte_type_attribute_value(self): | |
| with self.tracer.start_as_current_span("root") as root: | |
| - with self.assertLogs(level=WARNING): | |
| - root.set_attribute( | |
| - "invalid-byte-type-attribute", | |
| - b"\xd8\xe1\xb7\xeb\xa8\xe5 \xd2\xb7\xe1", | |
| - ) | |
| - self.assertFalse("invalid-byte-type-attribute" in root.attributes) | |
| - | |
| root.set_attribute("valid-byte-type-attribute", b"valid byte") | |
| - self.assertTrue(isinstance(root.attributes["valid-byte-type-attribute"], str)) | |
| + self.assertTrue(isinstance(root.attributes["valid-byte-type-attribute"], bytes)) | |
| def test_sampling_attributes(self): | |
| sampling_attributes = { | |
| class TestSpan(unittest.TestCase): | |
| with self.assertRaises(TypeError): | |
| event.attributes["name"] = "hello" | |
| - def test_invalid_event_attributes(self): | |
| + def test_setting_event_attributes(self): | |
| self.assertEqual(trace_api.get_current_span(), trace_api.INVALID_SPAN) | |
| with self.tracer.start_as_current_span("root") as root: | |
| - with self.assertLogs(level=WARNING): | |
| - root.add_event("event0", {"attr1": True, "attr2": ["hi", False]}) | |
| - with self.assertLogs(level=WARNING): | |
| - root.add_event("event0", {"attr1": {}}) | |
| - with self.assertLogs(level=WARNING): | |
| - root.add_event("event0", {"attr1": [[True]]}) | |
| - with self.assertLogs(level=WARNING): | |
| - root.add_event("event0", {"attr1": [{}], "attr2": [1, 2]}) | |
| + root.add_event("event0", {"attr1": True, "attr2": ["hi", False]}) | |
| + root.add_event("event0", {"attr1": {}}) | |
| + root.add_event("event0", {"attr1": [[True]]}) | |
| + root.add_event("event0", {"attr1": [{}], "attr2": [1, 2]}) | |
| self.assertEqual(len(root.events), 4) | |
| - self.assertEqual(root.events[0].attributes, {"attr1": True}) | |
| - self.assertEqual(root.events[1].attributes, {}) | |
| - self.assertEqual(root.events[2].attributes, {}) | |
| - self.assertEqual(root.events[3].attributes, {"attr2": (1, 2)}) | |
| + self.assertEqual( | |
| + root.events[0].attributes, | |
| + {"attr1": True, "attr2": ("hi", False)}, | |
| + ) | |
| + self.assertEqual(root.events[1].attributes, {"attr1": {}}) | |
| + self.assertEqual(root.events[2].attributes, {"attr1": ((True,),)}) | |
| + self.assertEqual(root.events[3].attributes, {"attr2": (1, 2), "attr1": ({},)}) | |
| def test_links(self): | |
| id_generator = RandomIdGenerator() | |
| diff --git a/pyproject.toml b/pyproject.toml | |
| index f7727d38..49039550 100644 | |
| --- a/pyproject.toml | |
| +++ b/pyproject.toml | |
| strict = [ | |
| "opentelemetry-semantic-conventions", | |
| "opentelemetry-sdk/src/opentelemetry/sdk/environment_variables", | |
| "opentelemetry-sdk/src/opentelemetry/sdk/resources", | |
| + "opentelemetry-api/src/opentelemetry/attributes/__init__.py", | |
| ] | |
| [tool.datamodel-codegen] | |