Skip to content

[bug] BoundedAttributes missing negative value validation for max_value_len parameter #5646

Description

@Dotify71

Describe your environment

OS: macOS / Linux
Python version: 3.10+
SDK version: main
API version: main

What happened?

In opentelemetry-api (opentelemetry.attributes.BoundedAttributes), passing a negative integer for maxlen (e.g. maxlen=-1) correctly validates the parameter and raises a ValueError("maxlen must be valid int greater or equal to 0").

However, max_value_len lacks validation for negative values. If a user initializes BoundedAttributes with a negative max_value_len (e.g. max_value_len=-1), no ValueError is raised. Instead, when string attributes are cleaned via _clean_attribute_value(), Python string slicing (value[:max_value_len]) chops characters off the end of strings instead of enforcing length limits, while logging misleading warning messages such as "String attribute value exceeds max length of -1, truncating.".

Steps to Reproduce

from opentelemetry.attributes import BoundedAttributes

1. maxlen validates negative inputs correctly:

try:
BoundedAttributes(maxlen=-1)
except ValueError as e:
print("maxlen validation working:", e)

2. max_value_len missing negative input validation:

ba = BoundedAttributes(max_value_len=-2, immutable=False)
ba["test_key"] = "hello world"

print(dict(ba))

Expected Result

Initializing BoundedAttributes with max_value_len < 0 should raise a ValueError("max_value_len must be valid int greater or equal to 0"), consistent with maxlen.

Actual Result

No ValueError is raised during __init__. The string is truncated unexpectedly from the right ({'test_key': 'hello wor'}), and an invalid warning log is emitted (String attribute value exceeds max length of -2, truncating.).

Additional context

Location in codebase: opentelemetry-api/src/opentelemetry/attributes/init.py

Suggested fix in BoundedAttributes.__init__:

if max_value_len is not None and max_value_len < 0:
    raise ValueError("max_value_len must be valid int greater or equal to 0")

### Would you like to implement a fix?

Yes

### Tip

<sub>[React](https://github.blog/news-insights/product-news/add-reactions-to-pull-requests-issues-and-comments/) with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding `+1` or `me too`, to help us triage it. Learn more [here](https://opentelemetry.io/community/end-user/issue-participation/).</sub>

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions