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
20 changes: 11 additions & 9 deletions lib/agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

'use strict'

const AdaptiveSampler = require('./samplers/adaptive-sampler')
const determineSampler = require('./samplers/determine-sampler')
const CollectorAPI = require('./collector/api')
const ServerlessCollector = require('./collector/serverless')
const DESTINATIONS = require('./config/attribute-filter').DESTINATIONS
Expand Down Expand Up @@ -287,12 +287,14 @@ function Agent(config) {
this.collector,
this.harvester
)
this.transactionSampler = new AdaptiveSampler({
agent: this,
serverless: config.serverless_mode.enabled,
period: config.sampling_target_period_in_seconds * 1000,
target: config.sampling_target
})

// Instantiate sampling decisions.
this.sampler = {}
// TODO: This could create duplicate AdaptiveSampler instances of the same
// `sampling_target`, fix will be addressed in https://github.com/newrelic/node-newrelic/issues/3519.
this.sampler.root = determineSampler({ agent: this, config, sampler: 'root' })
this.sampler.remoteParentSampled = determineSampler({ agent: this, config, sampler: 'remote_parent_sampled' })
this.sampler.remoteParentNotSampled = determineSampler({ agent: this, config, sampler: 'remote_parent_not_sampled' })

this.queries = new QueryTraceAggregator(
{
Expand Down Expand Up @@ -848,10 +850,10 @@ Agent.prototype._listenForConfigChanges = function _listenForConfigChanges() {
self.txSegmentNormalizer.load.apply(self.txSegmentNormalizer, arguments)
})
this.config.on('sampling_target', function updateSamplingTarget(target) {
self.transactionSampler.samplingTarget = target
self.sampler.root.samplingTarget = target
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So the transactionSampler is always the root sampler?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it was.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Though this updateSamplingTarget function does reveal another thing we will have to resolve with the sharing of AdaptiveSampler states, but that's out of scope for this PR.

})
this.config.on('sampling_target_period_in_seconds', function updateSamplePeriod(period) {
self.transactionSampler.samplingPeriod = period * 1000
self.sampler.root.samplingPeriod = period * 1000
})
this.config.on('event_harvest_config', function onHarvestConfigReceived(harvestConfig) {
if (harvestConfig) {
Expand Down
90 changes: 90 additions & 0 deletions lib/samplers/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Sampling at New Relic

The New Relic agent supports a robust sampling decision making interface. This is a work-in-progress feature.

## Config

Customers configure how they would like their transactions to be sampled under our `distributed_tracing` section in our config. Remember, sampling will only apply if a customer has `distributed_tracing.enabled` set to `true`.

### Types

- A "sampler mode" refers to the following config sections: `distributed_tracing.sampler`, `distributed_tracing.sampler.full_granularity`, and `distributed_tracing.sampler.partial_granularity`. They are defined by the three sections: `root`, `remote_parent_sampled`, and `remote_parent_not_sampled`.
- A "sampler section" refers to `root`, `remote_parent_sampled`, or `remote_parent_not_sampled` within a particular sampler mode. The config defined at this section, i.e. `SAMPLER_TYPE: SAMPLER_SUBOPTION?`, describes the sampling decision for that particular scenario within that mode.
- `root`: This is the main sampler for traces originating from the current service.
- `remote_parent_sampled`: The sampler for when the upstream service has sampled the trace.
- `remote_parent_not_sampled`: The sampler for when the upstream service has not sampled the trace.

NOTE: `distributed_tracing.sampler` only exists for backward compatiability and may be deprecated in favor of `distributed_tracing.sampler.full_granularity`. For now, `full_granularity` will take precedence over the old path.

### Full Config in Accordance to Spec

```yaml
...
(Serverless DT attributes; they may be defined under distributed_tracing instead)
account_id: string (unset by default, only set when using Serverless Mode)
trusted_account_key: string (unset by default, only set when using Serverless Mode)
primary_application_id: string (unset by default, only set when using Serverless Mode)
...
distributed_tracing:
enabled: boolean (default true)
exclude_newrelic_header: boolean (default false)
enable_success_metrics (OPTIONAL): boolean (default true, set to false to disable supportability metrics)
sampler: (section for sampling config options for different scenarios)
adaptive_sampling_target (see note on Sampling Target below)
root: (when the trace originates from the current service)
${SAMPLER_TYPE} (See `Sampler Options` below)
${SAMPLER_SUBOPTION}
remote_parent_sampled: (when the upstream service has sampled the trace)
${SAMPLER_TYPE} (See `Sampler Options` below)
${SAMPLER_SUBOPTION}
remote_parent_not_sampled: (when the upstream service has not sampled the trace)
${SAMPLER_TYPE}
${SAMPLER_SUBOPTION}
full_granularity:
enabled
root: (when the trace originates from the current service)
${SAMPLER_TYPE} (See `Sampler Options` below)
${SAMPLER_SUBOPTION}
remote_parent_sampled: (when the upstream service has sampled the trace)
${SAMPLER_TYPE} (See `Sampler Options` below)
${SAMPLER_SUBOPTION}
remote_parent_not_sampled: (when the upstream service has not sampled the trace)
${SAMPLER_TYPE}
${SAMPLER_SUBOPTION}
partial_granularity:
enabled
type ("reduced", "essential", "compact")
root: (when the trace originates from the current service)
${SAMPLER_TYPE} (See `Sampler Options` below)
${SAMPLER_SUBOPTION}
remote_parent_sampled: (when the upstream service has sampled the trace)
${SAMPLER_TYPE} (See `Sampler Options` below)
${SAMPLER_SUBOPTION}
remote_parent_not_sampled: (when the upstream service has not sampled the trace)
${SAMPLER_TYPE}
${SAMPLER_SUBOPTION}
...
```

## Solution

There are three sampler modes, each with three sampler sections, resulting in potentially nine different sampling decisions that the agent would have to support. We create a new `Sampler` instance (`AdaptiveSampler`, `AlwaysOnSampler`, `AlwaysOffSampler`, or `TraceIdRatioBasedSampler`, defined in this folder) for each of these sampler modes' sections.

`agent.sampler` would be defined as:

* `agent.sampler.fullGranularity.root`
* `agent.sampler.fullGranularity.remoteParentSampled`
* `agent.sampler.fullGranularity.remoteParentNotSampled`
* `agent.sampler.partialGranularity.root`
* `agent.sampler.partialGranularity.remoteParentSampled`
* `agent.sampler.partialGranularity.remoteParentNotSampled`

These fields currently exist (before core tracing was implemented); `agent.sampler.fullGranularity.*` will take precedence over these fields:

* `agent.sampler.root`
* `agent.sampler.remoteParentSampled`
* `agent.sampler.remoteParentNotSampled`

These samplers have a `applySamplingDecision({transaction})` function, which `Transaction` calls (in `lib/transaction/index.js`) to update its `sampled` field and therefore its `priority`.

Unlike the other samplers, the `AdaptiveSampler` must share state with other `AdaptiveSamplers` with the same `sampling_target`, which complicates our seperate sampler instances approach. This will be fixed shortly, and this document will be updated to describe that solution.
28 changes: 27 additions & 1 deletion lib/samplers/adaptive-sampler.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@

'use strict'

class AdaptiveSampler {
const Sampler = require('./sampler')

class AdaptiveSampler extends Sampler {
/**
*
* @param {object} opts Sampler options.
Expand All @@ -15,6 +17,7 @@ class AdaptiveSampler {
* @param {boolean} opts.serverless - Indicates if the environment is serverless.
*/
constructor(opts) {
super() // no-op
this._serverless = opts.serverless
this._seen = 0
this._sampled = 0
Expand All @@ -33,6 +36,10 @@ class AdaptiveSampler {
}
}

toString() {
return 'AdaptiveSampler'
}

get sampled() {
return this._sampled
}
Expand Down Expand Up @@ -99,6 +106,25 @@ class AdaptiveSampler {
return false
}

applySamplingDecision({ transaction, tracestate = null }) {
if (!transaction) return
if (tracestate) {
// Explicitly set sampled and priority from tracestate intrinsics if available
transaction.sampled = tracestate?.intrinsics ? tracestate.isSampled : null
transaction.priority = tracestate?.intrinsics ? tracestate.priority : null
return
}

// If a tracestate is not defined, then do our normal priority calculation.
// eslint-disable-next-line sonarjs/pseudo-random
const initPriority = Math.random()
transaction.sampled = this.shouldSample(initPriority)
transaction.priority = transaction.sampled ? initPriority + 1 : initPriority
// Truncate the priority after potentially modifying it to avoid floating
// point errors.
transaction.priority = ((transaction.priority * 1e6) | 0) / 1e6
}

/**
* Starts a new sample period after adjusting the sampling statistics.
*/
Expand Down
16 changes: 16 additions & 0 deletions lib/samplers/always-off-sampler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* Copyright 2025 New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/

const Sampler = require('./sampler')

class AlwaysOffSampler extends Sampler {
applySamplingDecision({ transaction }) {
if (!transaction) return
transaction.priority = 0
transaction.sampled = false
}
}

module.exports = AlwaysOffSampler
16 changes: 16 additions & 0 deletions lib/samplers/always-on-sampler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* Copyright 2025 New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/

const Sampler = require('./sampler')

class AlwaysOnSampler extends Sampler {
applySamplingDecision({ transaction }) {
if (!transaction) return
transaction.priority = 2.0
transaction.sampled = true
}
}

module.exports = AlwaysOnSampler
42 changes: 42 additions & 0 deletions lib/samplers/determine-sampler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright 2025 New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/

const AdaptiveSampler = require('./adaptive-sampler')
const AlwaysOffSampler = require('./always-off-sampler')
const AlwaysOnSampler = require('./always-on-sampler')

/**
* A helper function for the Agent to determine what sampler
* to use and will log messages about the chosen sampler.
* @param {*} params Function parameters.
* @param {Agent} params.agent The New Relic agent instance.
* @param {object} params.config The entire agent config.
* @param {string} params.sampler The sampler type to use: 'root', 'remote_parent_sampled', or 'remote_parent_not_sampled'.
* @returns {Sampler} A Sampler e.g. AdaptiveSampler
*/
function determineSampler({ agent, config, sampler = 'root' }) {
const samplerDefinition = config?.distributed_tracing?.sampler?.[sampler]

// Always on?
if (samplerDefinition === 'always_on') {
return new AlwaysOnSampler()
}

// Always off?
if (samplerDefinition === 'always_off') {
return new AlwaysOffSampler()
}

// Our default ^.^
// We'll ignore https://github.com/newrelic/node-newrelic/issues/3519 for now 0.o
return new AdaptiveSampler({
agent,
serverless: config.serverless_mode.enabled,
period: config.sampling_target_period_in_seconds * 1000,
target: config.sampling_target // getter/setter for distributed_tracing.sampler.adaptive_sampling_target
})
}

module.exports = determineSampler
22 changes: 22 additions & 0 deletions lib/samplers/sampler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* Copyright 2025 New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/

/**
* @private
* @interface
*/
class Sampler {
/**
* Sets `priority` and `sampled` on the transaction
* in respect to this sampler's decision.
* @param {object} params to make the sampling decision with
* @param {Transaction} params.transaction the transaction to update
*/
applySamplingDecision({ transaction }) {
throw new Error('must implement applySamplingDecision for %s', transaction)
}
}

module.exports = Sampler
Loading
Loading