Skip to content

fix(tracing): Fix InvalidOperation #4179

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions sentry_sdk/tracing_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import sys
from collections.abc import Mapping
from datetime import timedelta
from decimal import ROUND_DOWN, Decimal
from decimal import ROUND_DOWN, Context, Decimal
from functools import wraps
from random import Random
from urllib.parse import quote, unquote
Expand Down Expand Up @@ -871,7 +871,11 @@ def _generate_sample_rand(
sample_rand = rng.uniform(lower, upper)

# Round down to exactly six decimal-digit precision.
return Decimal(sample_rand).quantize(Decimal("0.000001"), rounding=ROUND_DOWN)
# Setting the context is needed to avoid an InvalidOperation exception
# in case the user has changed the default precision.
return Decimal(sample_rand).quantize(
Decimal("0.000001"), rounding=ROUND_DOWN, context=Context(prec=6)
)


def _sample_rand_range(parent_sampled, sample_rate):
Expand Down
26 changes: 26 additions & 0 deletions tests/tracing/test_sample_rand.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import decimal
from unittest import mock

import pytest
Expand Down Expand Up @@ -53,3 +54,28 @@ def test_transaction_uses_incoming_sample_rand(
# Transaction event captured if sample_rand < sample_rate, indicating that
# sample_rand is used to make the sampling decision.
assert len(events) == int(sample_rand < sample_rate)


def test_decimal_context(sentry_init, capture_events):
"""
Ensure that having a decimal context with a precision below 6
does not cause an InvalidOperation exception.
"""
sentry_init(traces_sample_rate=1.0)
events = capture_events()

old_prec = decimal.getcontext().prec
decimal.getcontext().prec = 2

try:
with mock.patch(
"sentry_sdk.tracing_utils.Random.uniform", return_value=0.123456789
):
with sentry_sdk.start_transaction() as transaction:
assert (
transaction.get_baggage().sentry_items["sample_rand"] == "0.123456"
)
finally:
decimal.getcontext().prec = old_prec

assert len(events) == 1
Loading