Skip to content
This repository was archived by the owner on Aug 30, 2022. It is now read-only.

Commit a1bea40

Browse files
rnburnisaachier
authored andcommitted
Fix overflow bug. (#13)
1 parent 64f66e3 commit a1bea40

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

src/jaegertracing/samplers/ProbabilisticSampler.h

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,7 @@ class ProbabilisticSampler : public Sampler {
2727
public:
2828
explicit ProbabilisticSampler(double samplingRate)
2929
: _samplingRate(std::max(0.0, std::min(samplingRate, 1.0)))
30-
, _samplingBoundary(
31-
static_cast<uint64_t>(kMaxRandomNumber * _samplingRate))
30+
, _samplingBoundary(computeSamplingBoundary(_samplingRate))
3231
, _tags({ { kSamplerTypeTagKey, kSamplerTypeProbabilistic },
3332
{ kSamplerParamTagKey, _samplingRate } })
3433
{
@@ -53,6 +52,20 @@ class ProbabilisticSampler : public Sampler {
5352
double _samplingRate;
5453
uint64_t _samplingBoundary;
5554
std::vector<Tag> _tags;
55+
56+
static uint64_t computeSamplingBoundary(long double samplingRate)
57+
{
58+
const long double maxRandNumber = kMaxRandomNumber;
59+
const auto samplingBoundary = samplingRate * maxRandNumber;
60+
61+
// Protect against overflow in case samplingBoundary rounds
62+
// higher than kMaxRandNumber.
63+
if (samplingBoundary == maxRandNumber) {
64+
return kMaxRandomNumber;
65+
}
66+
67+
return static_cast<uint64_t>(samplingBoundary);
68+
}
5669
};
5770

5871
} // namespace samplers

src/jaegertracing/samplers/SamplerTest.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ TEST(Sampler, testProbabilisticSamplerErrors)
105105

106106
TEST(Sampler, testProbabilisticSampler)
107107
{
108+
{
108109
ProbabilisticSampler sampler(0.5);
109110
auto result =
110111
sampler.isSampled(TraceID(0, kTestMaxID + 10), kTestOperationName);
@@ -114,6 +115,16 @@ TEST(Sampler, testProbabilisticSampler)
114115
result = sampler.isSampled(TraceID(0, kTestMaxID - 20), kTestOperationName);
115116
ASSERT_TRUE(result.isSampled());
116117
CMP_TAGS(testProbablisticExpectedTags, result.tags());
118+
}
119+
{
120+
ProbabilisticSampler sampler(1.0);
121+
auto result =
122+
sampler.isSampled(TraceID(0, kTestMaxID), kTestOperationName);
123+
ASSERT_TRUE(result.isSampled());
124+
125+
result = sampler.isSampled(TraceID(0, kTestMaxID - 20), kTestOperationName);
126+
ASSERT_TRUE(result.isSampled());
127+
}
117128
}
118129

119130
TEST(Sampler, testProbabilisticSamplerPerformance)

0 commit comments

Comments
 (0)