Skip to content

opentelemetry-api: prevent recursive attribute value crashes - #5983

Open
csw7777 wants to merge 4 commits into
open-telemetry:mainfrom
csw7777:fix/attribute-nesting-depth-assisted
Open

csw7777 wants to merge 4 commits into
open-telemetry:mainfrom
csw7777:fix/attribute-nesting-depth-assisted

Conversation

@csw7777

@csw7777 csw7777 commented Nov 29, 2026 •

Copy link
Copy Markdown

Replaces #5976. Uses OpenTelemetry's Assisted-by AI disclosure convention while retaining csw7777 as the sole human commit author.

Summary

Fixes #5564.

  • Track active ancestor container IDs to reject cycles immediately, avoiding exponential traversal for branching cycles while allowing non-cyclic shared references. Ancestor tracking is allocated lazily, and scalar values use a fast path.
  • Remove obsolete _clean_attribute_value overloads and apply the depth limit consistently to empty and non-empty containers.
  • Bound recursive attribute cleaning to 20 levels, replacing excessively nested values with None instead of leaking RecursionError into application code.
  • Clean top-level attribute values independently so an invalid value does not discard valid siblings.
  • Apply the same isolation to metric Measurement attributes.
  • Add regression coverage for cyclic sequences and mappings, the exact depth boundary, spans, resources, BoundedAttributes, and metric measurements.

This follows the 20-level approach previously reviewed in #5565 and #5757. In particular, it adds the metrics regression coverage requested in #5757 and reapplies the fix onto current main.

Compatibility

Only values that previously caused RecursionError are affected. Valid values at the supported depth remain intact, and valid sibling attributes are preserved. A warning is emitted when a value is replaced with None.

Validation

  • Focused API/SDK suites: 98 passed, 16 subtests passed.
  • The 13 new regression tests all pass.
  • pyright on the changed API source and test file: 0 errors, 0 warnings.
  • ruff format and ruff check on every changed Python file: passed.
  • pylint on every changed Python file: passed, 10.00/10.

The focused suites were:

python -m pytest opentelemetry-api/tests/attributes \
  opentelemetry-sdk/tests/test_attribute_nesting_depth.py \
  opentelemetry-sdk/tests/metrics/test_metrics.py -q -o addopts=""

🤖 Generated with Kimi

Bound attribute nesting at 20 levels and replace cyclic or deeper values
with None. Clean top-level attributes independently so invalid values do not
discard valid siblings in spans, resources, and metric measurements.

Add API, SDK, resource, and measurement regression tests.

Fixes open-telemetry#5564

Assisted-by: Kimi
@csw7777
csw7777 requested a review from a team as a code owner November 29, 2026 05:32
@opentelemetry-pr-dashboard

opentelemetry-pr-dashboard Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Pull request dashboard status

Waiting on the author · refreshed 2026-12-02 18:08 UTC

Respond to 2 review items (e.g. link a commit, explain why not, ask a follow-up):

  • Inline threads: 1
  • Top-level threads: 2
Status above doesn't look right?
  • Just replied or pushed? Anything around or after the refresh time above may not be picked up yet — give it a few minutes.
  • Should this be with reviewers? Comment /dashboard route:reviewers to route it to them.
  • Anything wrong — including the routing? Report it with what you expected; it helps us improve the dashboard.

@DylanRussell DylanRussell left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for picking this up! The cycle detection and top-level isolation look good overall — a few items to address:

  • The @overload stubs on _clean_attribute_value (opentelemetry-api/src/opentelemetry/attributes/__init__.py lines 36–47) are now unused (since _set_items calls _clean_attributes) and no longer accurate: passing a cyclic or overly nested Mapping now returns None, not Mapping[str, types.AnyValue]. Those overloads can be removed.
  • See inline comments below (in particular, pyright currently fails on the new API test file).


def _cyclic_list():
value = [1, 2]
value.append(value)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pyright (tox -e typecheck) currently fails with 7 errors on this file (unlike test_attributes.py, this file doesn't opt out of type checking):

  • Line 11: value = [1, 2]; value.append(value) — list[int] not assignable to int (reportArgumentType)
  • Line 29: value = {"value": 1}; value["self"] = value — dict[str, int] not assignable to int (reportArgumentType)
  • Line 37: cleaned = cleaned[0] — self.assertIsInstance(cleaned, tuple) doesn't narrow AnyValue in pyright (reportIndexIssue / reportArgumentType / reportOptionalSubscript)

Annotating value: list[Any] = [1, 2] / value: dict[str, Any] = {"value": 1} and narrowing cleaned (e.g. assert isinstance(cleaned, tuple)) should clear these.

The recursively cleaned AnyValue.
"""
try:
return _clean_attribute_value_impl(value, max_value_length, 0, set())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This allocates a new set() and makes an extra _clean_attribute_value_impl call on every attribute value, including primitives (str, int, float, bool, None), which make up the vast majority of attributes. Fast-pathing primitives here (or lazily allocating ancestors only when encountering (Sequence, Mapping)) avoids that overhead on the hot path.

depth: int,
ancestors: set[int],
) -> types.AnyValue:
if depth > _MAX_NESTING_DEPTH:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor nit: checking depth > _MAX_NESTING_DEPTH at entry allows 21 nested empty containers (e.g. [[...[]...]], where the 21st container is at depth == 20 and never recurses), whereas 21 nested non-empty containers are rejected.

Comment thread .changelog/5983.fixed Outdated
@@ -0,0 +1 @@
Prevent cyclic or excessively nested attribute values from raising `RecursionError`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: consider prefixing with the affected packages to match existing changelog entries:

Suggested change
Prevent cyclic or excessively nested attribute values from raising `RecursionError`.
`opentelemetry-api`, `opentelemetry-sdk`: prevent cyclic or excessively nested attribute values from raising `RecursionError`.

Remove obsolete overloads, fast-path scalar attributes, allocate ancestor
tracking lazily, and reject excessive empty containers consistently. Fix
test typing and name the affected packages in the changelog.

Assisted-by: Kimi

This branch has not been deployed

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

Labels

None yet

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

Self-referential attribute value crashes the instrumented application with RecursionError

2 participants