Skip to content
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
9 changes: 6 additions & 3 deletions packages/dd-trace/src/priority_sampler.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,16 @@ const {
const DEFAULT_KEY = 'service:,env:'

/**
* Formats a sampling rate as a string with up to 6 significant digits and no trailing zeros.
* Formats a sampling rate as a string with up to 6 decimal digits and no trailing zeros.
*
* @param {number} rate
* @returns {string}
*/
function formatKnuthRate (rate) {
return Number(rate.toPrecision(6)).toString()
const string = Number(rate).toFixed(6)
for (let i = string.length - 1; i > 0; i--) {
if (string[i] === '0') continue
return string.slice(0, i + (string[i] === '.' ? 0 : 1))
}
}

const defaultSampler = new Sampler(AUTO_KEEP)
Expand Down
39 changes: 39 additions & 0 deletions packages/dd-trace/test/priority_sampler.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,45 @@ describe('PrioritySampler', () => {
assert.strictEqual(typeof context._trace.tags[SAMPLING_KNUTH_RATE], 'string')
})

it('should format _dd.p.ksr with decimal notation for very small rates', () => {
Sampler.withArgs(0.000001).returns({
isSampled: sinon.stub().returns(true),
rate: sinon.stub().returns(0.000001),
})
prioritySampler = new PrioritySampler('test', {
sampleRate: 0.000001,
})
prioritySampler.sample(span)

assert.strictEqual(context._trace.tags[SAMPLING_KNUTH_RATE], '0.000001')
})

it('should round _dd.p.ksr to zero when rate is below 6 decimal precision', () => {
Sampler.withArgs(0.0000001).returns({
isSampled: sinon.stub().returns(true),
rate: sinon.stub().returns(0.0000001),
})
prioritySampler = new PrioritySampler('test', {
sampleRate: 0.0000001,
})
prioritySampler.sample(span)

assert.strictEqual(context._trace.tags[SAMPLING_KNUTH_RATE], '0')
})

it('should round _dd.p.ksr up to 0.000001 when rate rounds up', () => {
Sampler.withArgs(0.00000051).returns({
isSampled: sinon.stub().returns(true),
rate: sinon.stub().returns(0.00000051),
})
prioritySampler = new PrioritySampler('test', {
sampleRate: 0.00000051,
})
prioritySampler.sample(span)

assert.strictEqual(context._trace.tags[SAMPLING_KNUTH_RATE], '0.000001')
})

it('should not set _dd.p.ksr tag for manual sampling', () => {
context._tags[MANUAL_KEEP] = undefined

Expand Down
Loading