diff --git a/packages/dd-trace/src/priority_sampler.js b/packages/dd-trace/src/priority_sampler.js index 4e586bc6a93..6edfc39c81a 100644 --- a/packages/dd-trace/src/priority_sampler.js +++ b/packages/dd-trace/src/priority_sampler.js @@ -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) diff --git a/packages/dd-trace/test/priority_sampler.spec.js b/packages/dd-trace/test/priority_sampler.spec.js index 39bbf2f153e..7e2c821b012 100644 --- a/packages/dd-trace/test/priority_sampler.spec.js +++ b/packages/dd-trace/test/priority_sampler.spec.js @@ -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