dd-trace 6.22.0 → 6.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/LICENSE-3rdparty.csv +0 -1
  2. package/ci/cypress/support.js +15 -1
  3. package/ci/diagnose.js +4 -4
  4. package/ci/test-annotations.d.ts +5 -0
  5. package/ci/test-annotations.js +5 -0
  6. package/ci/test-optimization-validation/approval-artifacts.js +2 -2
  7. package/ci/test-optimization-validation/approval.js +2 -2
  8. package/ci/test-optimization-validation/artifact-id.js +2 -3
  9. package/ci/test-optimization-validation/ci-package-scripts.js +1 -1
  10. package/ci/test-optimization-validation/cli.js +1 -1
  11. package/ci/test-optimization-validation/command-runner.js +2 -3
  12. package/ci/test-optimization-validation/executable.js +1 -1
  13. package/ci/test-optimization-validation/framework-adapters/cucumber.js +1 -1
  14. package/ci/test-optimization-validation/literal-environment.js +2 -2
  15. package/ci/test-optimization-validation/manifest-scaffold.js +1 -1
  16. package/ci/test-optimization-validation/offline-fixtures.js +1 -1
  17. package/ci/test-optimization-validation/redaction.js +3 -3
  18. package/ci/test-optimization-validation/runner-contract.js +10 -10
  19. package/ci/test-optimization-validation/scenarios/ci-wiring.js +1 -1
  20. package/ci/vitest-no-worker-init-annotations.mjs +4 -0
  21. package/ci/vitest-no-worker-init-node-setup.mjs +22 -0
  22. package/ci/vitest-no-worker-init-runner-setup.mjs +7 -5
  23. package/ci/vitest-no-worker-init-setup.mjs +34 -12
  24. package/ci/vitest-no-worker-init-v5-setup.mjs +6 -0
  25. package/ext/exporters.js +1 -0
  26. package/index.d.ts +35 -5
  27. package/loader-hook.mjs +53 -0
  28. package/openfeature/exposure-hook.d.ts +66 -0
  29. package/openfeature/exposure-hook.js +5 -0
  30. package/package.json +23 -20
  31. package/packages/datadog-core/src/storage.js +1 -1
  32. package/packages/datadog-esbuild/index.js +70 -7
  33. package/packages/datadog-instrumentations/index.js +2 -1
  34. package/packages/datadog-instrumentations/src/cucumber.js +64 -21
  35. package/packages/datadog-instrumentations/src/cypress-config.js +163 -15
  36. package/packages/datadog-instrumentations/src/graphql.js +9 -3
  37. package/packages/datadog-instrumentations/src/grpc/server.js +23 -6
  38. package/packages/datadog-instrumentations/src/helpers/bundler-register.js +27 -8
  39. package/packages/datadog-instrumentations/src/helpers/fetch.js +5 -1
  40. package/packages/datadog-instrumentations/src/helpers/graphql-jit-runtime.js +30 -8
  41. package/packages/datadog-instrumentations/src/helpers/hooks.js +2 -1
  42. package/packages/datadog-instrumentations/src/helpers/register.js +9 -0
  43. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +16 -6
  44. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +10 -0
  45. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql-jit.js +3 -1
  46. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/jest.js +12 -0
  47. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/react-router.js +49 -0
  48. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/typesafe.js +23 -0
  49. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/vitest.js +8 -0
  50. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/webdriverio.js +12 -0
  51. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +8 -0
  52. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.js +19 -2
  53. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +13 -0
  54. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +1 -1
  55. package/packages/datadog-instrumentations/src/jest.js +332 -137
  56. package/packages/datadog-instrumentations/src/mariadb-bundle.js +69 -11
  57. package/packages/datadog-instrumentations/src/mariadb.js +13 -6
  58. package/packages/datadog-instrumentations/src/mocha/common.js +89 -8
  59. package/packages/datadog-instrumentations/src/mocha/main.js +11 -2
  60. package/packages/datadog-instrumentations/src/mocha/utils.js +92 -13
  61. package/packages/datadog-instrumentations/src/mocha/worker.js +1 -1
  62. package/packages/datadog-instrumentations/src/nova-sonic/session.js +25 -16
  63. package/packages/datadog-instrumentations/src/oracledb.js +33 -0
  64. package/packages/datadog-instrumentations/src/pg.js +2 -1
  65. package/packages/datadog-instrumentations/src/playwright.js +81 -26
  66. package/packages/datadog-instrumentations/src/react-router.js +106 -0
  67. package/packages/datadog-instrumentations/src/stripe.js +23 -12
  68. package/packages/datadog-instrumentations/src/typesafe.js +89 -0
  69. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +84 -47
  70. package/packages/datadog-instrumentations/src/vitest-main.js +33 -3
  71. package/packages/datadog-instrumentations/src/vitest-test-annotations.js +20 -0
  72. package/packages/datadog-instrumentations/src/vitest-util.js +5 -2
  73. package/packages/datadog-instrumentations/src/vitest-worker.js +39 -17
  74. package/packages/datadog-instrumentations/src/vitest.js +16 -6
  75. package/packages/datadog-plugin-cucumber/src/index.js +5 -0
  76. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +277 -44
  77. package/packages/datadog-plugin-cypress/src/index.js +1 -1
  78. package/packages/datadog-plugin-cypress/src/lifecycle-owner.js +20 -0
  79. package/packages/datadog-plugin-cypress/src/plugin.js +10 -0
  80. package/packages/datadog-plugin-cypress/src/retry-config-observer.js +281 -0
  81. package/packages/datadog-plugin-cypress/src/setup-handoff.js +125 -0
  82. package/packages/datadog-plugin-cypress/src/support.js +1217 -437
  83. package/packages/datadog-plugin-graphql/src/execute.js +2 -2
  84. package/packages/datadog-plugin-graphql/src/utils.js +5 -5
  85. package/packages/datadog-plugin-jest/src/index.js +25 -3
  86. package/packages/datadog-plugin-mocha/src/index.js +47 -6
  87. package/packages/datadog-plugin-oracledb/src/connection-parser.js +21 -11
  88. package/packages/datadog-plugin-playwright/src/index.js +4 -0
  89. package/packages/datadog-plugin-react-router/src/index.js +118 -0
  90. package/packages/datadog-plugin-typesafe/src/index.js +17 -0
  91. package/packages/datadog-plugin-typesafe/src/tracing.js +31 -0
  92. package/packages/datadog-plugin-vitest/src/index.js +8 -0
  93. package/packages/dd-trace/src/agent/info.js +2 -1
  94. package/packages/dd-trace/src/aiguard/evaluation.js +143 -1
  95. package/packages/dd-trace/src/aiguard/sdk.js +0 -11
  96. package/packages/dd-trace/src/appsec/iast/path-line.js +2 -1
  97. package/packages/dd-trace/src/appsec/stack_trace.js +3 -2
  98. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/worker/index.js +3 -2
  99. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +9 -16
  100. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +4 -2
  101. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +9 -16
  102. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +9 -14
  103. package/packages/dd-trace/src/ci-visibility/requests/route.js +44 -0
  104. package/packages/dd-trace/src/ci-visibility/telemetry-logs.js +5 -0
  105. package/packages/dd-trace/src/ci-visibility/test-annotations.js +72 -0
  106. package/packages/dd-trace/src/ci-visibility/test-declaration-annotations.js +170 -0
  107. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +9 -16
  108. package/packages/dd-trace/src/config/defaults.js +4 -3
  109. package/packages/dd-trace/src/config/generated-config-types.d.ts +6 -0
  110. package/packages/dd-trace/src/config/index.js +140 -39
  111. package/packages/dd-trace/src/config/parsers.js +9 -1
  112. package/packages/dd-trace/src/config/supported-configurations.json +25 -0
  113. package/packages/dd-trace/src/debugger/devtools_client/breakpoints.js +6 -5
  114. package/packages/dd-trace/src/debugger/devtools_client/condition.js +5 -5
  115. package/packages/dd-trace/src/debugger/devtools_client/snapshot/collector.js +4 -6
  116. package/packages/dd-trace/src/debugger/probe_sampler.js +6 -6
  117. package/packages/dd-trace/src/debugger/unsupported-runtime.js +16 -0
  118. package/packages/dd-trace/src/encode/0.4.js +2 -2
  119. package/packages/dd-trace/src/esm-module-load.js +58 -0
  120. package/packages/dd-trace/src/exporter.js +25 -6
  121. package/packages/dd-trace/src/exporters/agent/index.js +3 -1
  122. package/packages/dd-trace/src/exporters/agentless/index.js +3 -1
  123. package/packages/dd-trace/src/exporters/common/request.js +4 -4
  124. package/packages/dd-trace/src/exporters/llmobs/index.js +135 -0
  125. package/packages/dd-trace/src/exporters/log/index.js +4 -3
  126. package/packages/dd-trace/src/llmobs/agent-manifest.js +19 -2
  127. package/packages/dd-trace/src/llmobs/constants/tags.js +4 -0
  128. package/packages/dd-trace/src/llmobs/experiments/index.js +2 -3
  129. package/packages/dd-trace/src/llmobs/experiments/noop.js +5 -2
  130. package/packages/dd-trace/src/llmobs/index.js +13 -2
  131. package/packages/dd-trace/src/llmobs/plugins/claude-agent-sdk/index.js +1 -1
  132. package/packages/dd-trace/src/llmobs/plugins/genai/index.js +1 -1
  133. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +8 -4
  134. package/packages/dd-trace/src/llmobs/plugins/openai/constants.js +5 -0
  135. package/packages/dd-trace/src/llmobs/plugins/openai/index.js +9 -1
  136. package/packages/dd-trace/src/llmobs/plugins/typesafe/index.js +102 -0
  137. package/packages/dd-trace/src/llmobs/prompts/cache.js +3 -1
  138. package/packages/dd-trace/src/llmobs/sdk.js +17 -5
  139. package/packages/dd-trace/src/llmobs/span_processor.js +222 -12
  140. package/packages/dd-trace/src/llmobs/tagger.js +21 -8
  141. package/packages/dd-trace/src/llmobs/util.js +10 -4
  142. package/packages/dd-trace/src/llmobs/writers/util.js +3 -3
  143. package/packages/dd-trace/src/log/writer.js +7 -1
  144. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +64 -6
  145. package/packages/dd-trace/src/openfeature/configuration_source.js +18 -2
  146. package/packages/dd-trace/src/openfeature/debug-logging-hook.js +66 -3
  147. package/packages/dd-trace/src/openfeature/exposure-hook.js +185 -0
  148. package/packages/dd-trace/src/openfeature/flagging_provider.js +39 -13
  149. package/packages/dd-trace/src/openfeature/index.js +6 -0
  150. package/packages/dd-trace/src/openfeature/remote_config.js +16 -3
  151. package/packages/dd-trace/src/openfeature/writers/base.js +62 -27
  152. package/packages/dd-trace/src/openfeature/writers/exposures.js +161 -1
  153. package/packages/dd-trace/src/openfeature/writers/flag-eval-evp-hook.js +5 -0
  154. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-aggregation.js +9 -4
  155. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-payload.js +2 -0
  156. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-pii.js +2 -0
  157. package/packages/dd-trace/src/openfeature/writers/split-features.js +25 -0
  158. package/packages/dd-trace/src/openfeature/writers/util.js +4 -4
  159. package/packages/dd-trace/src/opentelemetry/metrics/periodic_metric_reader.js +2 -2
  160. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +18 -1
  161. package/packages/dd-trace/src/opentelemetry/tracer_provider.js +5 -1
  162. package/packages/dd-trace/src/opentracing/tracer.js +9 -13
  163. package/packages/dd-trace/src/otel-thread-ctx.js +47 -21
  164. package/packages/dd-trace/src/plugin_manager.js +1 -2
  165. package/packages/dd-trace/src/plugins/ci_plugin.js +4 -4
  166. package/packages/dd-trace/src/plugins/index.js +3 -0
  167. package/packages/dd-trace/src/plugins/tracing.js +1 -2
  168. package/packages/dd-trace/src/plugins/util/git.js +102 -40
  169. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +2 -4
  170. package/packages/dd-trace/src/plugins/util/stacktrace.js +2 -1
  171. package/packages/dd-trace/src/plugins/util/test.js +28 -6
  172. package/packages/dd-trace/src/plugins/util/web.js +106 -20
  173. package/packages/dd-trace/src/process-tags/index.js +1 -1
  174. package/packages/dd-trace/src/profiling/config.js +6 -3
  175. package/packages/dd-trace/src/proxy.js +15 -4
  176. package/packages/dd-trace/src/serverless.js +3 -2
  177. package/packages/dd-trace/src/span_processor.js +21 -9
  178. package/packages/dd-trace/src/span_stats.js +32 -3
  179. package/packages/dd-trace/src/startup-log.js +2 -1
  180. package/packages/dd-trace/src/tagger.js +7 -5
  181. package/packages/dd-trace/src/telemetry/dependencies.js +4 -0
  182. package/packages/dd-trace/src/telemetry/index.js +3 -0
  183. package/packages/dd-trace/src/telemetry/logs/index.js +21 -2
  184. package/packages/dd-trace/src/telemetry/logs/log-collector.js +2 -1
  185. package/packages/dd-trace/src/telemetry/telemetry.js +10 -3
  186. package/packages/dd-trace/src/util.js +9 -5
  187. package/register.js +2 -1
  188. package/vendor/dist/@apm-js-collab/code-transformer/index.js +8 -8
  189. package/vendor/dist/@datadog/openfeature-node-server/index.js +1 -1
  190. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.d.ts +78 -0
  191. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.js +1 -1
  192. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  193. package/vendor/dist/@opentelemetry/resources/LICENSE +0 -201
  194. package/vendor/dist/@opentelemetry/resources/index.js +0 -1
@@ -103,14 +103,14 @@ async function addBreakpoint (probe) {
103
103
  file, lineNumber, columnNumber, probe.id, probe.version
104
104
  )
105
105
  const position = await getGeneratedPosition(url, source, lineNumber, sourceMapURL)
106
- if (position.line !== null && position.column !== null) {
107
- lineNumber = position.line
108
- columnNumber = position.column
109
- } else {
106
+ if (position.line === null || position.column === null) {
110
107
  throw new Error(
111
108
  // eslint-disable-next-line @stylistic/max-len
112
109
  `Could not find generated position for ${url}:${lineNumber}:${columnNumber} (probe: ${probe.id}, version: ${probe.version})`
113
110
  )
111
+ } else {
112
+ lineNumber = position.line
113
+ columnNumber = position.column
114
114
  }
115
115
  }
116
116
 
@@ -357,9 +357,10 @@ async function reEvaluateProbe (probe) {
357
357
  }
358
358
 
359
359
  async function start () {
360
- sessionStarted = true
361
360
  log.debug('[debugger:devtools_client] Starting debugger')
362
361
  await session.post('Debugger.enable')
362
+ // Only flag the session as started once enabled, so the next probe retries a failed start and reports its cause
363
+ sessionStarted = true
363
364
 
364
365
  // Wait until there's a pause in script-loading to avoid accidentally adding probes to incorrect scripts. This is not
365
366
  // a guarantee, but best effort.
@@ -312,9 +312,9 @@ function isInstanceOfCoreType (type, variable, fallback = `${variable} instanceo
312
312
  function getSize (variable) {
313
313
  return `((val) => {
314
314
  if (${isString('val')} || ${isArrayOrTypedArray('val')}) {
315
- return ${guardAgainstPropertyAccessSideEffects('val', '"length"')}
315
+ return ${guardAgainstPropertyAccessSideEffects('"length"')}
316
316
  } else if (${isInstanceOfCoreType('Set', 'val')} || ${isInstanceOfCoreType('Map', 'val')}) {
317
- return ${guardAgainstPropertyAccessSideEffects('val', '"size"')}
317
+ return ${guardAgainstPropertyAccessSideEffects('"size"')}
318
318
  } else if (${isInstanceOfCoreType('WeakSet', 'val')} || ${isInstanceOfCoreType('WeakMap', 'val')}) {
319
319
  throw new TypeError('Cannot get size of WeakSet or WeakMap')
320
320
  } else if (typeof val === 'object' && val !== null) {
@@ -338,12 +338,12 @@ function accessProperty (variable, keyOrIndex, allowMapAccess) {
338
338
  } else if (${isInstanceOfCoreType('Set', 'val')} || ${isInstanceOfCoreType('WeakSet', 'val')}) {
339
339
  throw new Error('Accessing a Set or WeakSet is not allowed')
340
340
  } else {
341
- return ${guardAgainstPropertyAccessSideEffects('val', 'key')}
341
+ return ${guardAgainstPropertyAccessSideEffects('key')}
342
342
  }
343
343
  })(${variable}, ${keyOrIndex})`
344
344
  }
345
345
 
346
- function guardAgainstPropertyAccessSideEffects (variable, propertyName) {
346
+ function guardAgainstPropertyAccessSideEffects (propertyName) {
347
347
  return `((val, key) => {
348
348
  if (
349
349
  ${isInstanceOfCoreType('Proxy', 'val', 'true')} ||
@@ -353,7 +353,7 @@ function guardAgainstPropertyAccessSideEffects (variable, propertyName) {
353
353
  } else {
354
354
  return val[key]
355
355
  }
356
- })(${variable}, ${propertyName})`
356
+ })(val, ${propertyName})`
357
357
  }
358
358
 
359
359
  function guardAgainstCoercionSideEffects (variable) {
@@ -126,8 +126,8 @@ async function traverseGetPropertiesResult (props, opts, depth) {
126
126
  if (prop.value === undefined) continue
127
127
  const { value: { type, objectId, subtype, description } } = prop
128
128
  if (type === 'object') {
129
- if (objectId === undefined) continue // if `subtype` is "null"
130
- if (LEAF_SUBTYPES.has(subtype)) continue // don't waste time with these subtypes
129
+ // if `subtype` is "null"
130
+ if (objectId === undefined || LEAF_SUBTYPES.has(subtype)) continue // don't waste time with these subtypes
131
131
  const size = parseLengthFromDescription(description, subtype)
132
132
  if (size !== null && size >= LARGE_OBJECT_SKIP_THRESHOLD) {
133
133
  const empty = []
@@ -310,8 +310,7 @@ function removeNonEnumerableProperties (props) {
310
310
  }
311
311
 
312
312
  function parseLengthFromDescription (description, subtype) {
313
- if (typeof description !== 'string') return null
314
- if (!SIZE_IN_DESCRIPTION_SUBTYPES.has(subtype)) return null
313
+ if (typeof description !== 'string' || !SIZE_IN_DESCRIPTION_SUBTYPES.has(subtype)) return null
315
314
 
316
315
  const open = description.lastIndexOf('(')
317
316
  if (open === -1) return null
@@ -323,8 +322,7 @@ function parseLengthFromDescription (description, subtype) {
323
322
  if (s === '') return null
324
323
 
325
324
  const n = Number(s)
326
- if (!Number.isSafeInteger(n) || n < 0) return null
327
- if (String(n) !== s) return null
325
+ if (!Number.isSafeInteger(n) || n < 0 || String(n) !== s) return null
328
326
 
329
327
  return n
330
328
  }
@@ -152,7 +152,7 @@ function installProbeSampler (guardrailMetrics, config) {
152
152
  if (elapsedNs > evaluationTimeoutNs) {
153
153
  return recordConditionError(probeIndex, probeId, now, describeTimeout(elapsedNs), true)
154
154
  }
155
- return matched === true && sample(probeIndex, probeId, now, nsBetweenSampling, isSnapshotProducingProbe)
155
+ return matched && sample(probeIndex, probeId, now, nsBetweenSampling, isSnapshotProducingProbe)
156
156
  },
157
157
 
158
158
  /**
@@ -235,7 +235,7 @@ function installProbeSampler (guardrailMetrics, config) {
235
235
  if (state.timedOut) {
236
236
  guardrailMetrics.eventSkipped(
237
237
  SKIPPED_REASON.EVALUATION_TIMEOUT,
238
- isSnapshotProducingProbe === true ? EVENT_TYPE.SNAPSHOT : EVENT_TYPE.LOG
238
+ isSnapshotProducingProbe ? EVENT_TYPE.SNAPSHOT : EVENT_TYPE.LOG
239
239
  )
240
240
  }
241
241
  return true
@@ -254,7 +254,7 @@ function installProbeSampler (guardrailMetrics, config) {
254
254
  * @param {boolean} isSnapshotProducingProbe - Whether this probe counts toward the global snapshot sample limit.
255
255
  */
256
256
  function sample (probeIndex, probeId, now, nsBetweenSampling, isSnapshotProducingProbe) {
257
- if (isSnapshotProducingProbe === true) {
257
+ if (isSnapshotProducingProbe) {
258
258
  const span = /** @type {ActiveSpan | null | undefined} */ (legacyStorage.getStore()?.span)
259
259
  const trace = span?.context()._trace
260
260
  // The span processor empties `started` once all spans of a trace have finished. A probe hit under such a trace
@@ -320,12 +320,12 @@ function installProbeSampler (guardrailMetrics, config) {
320
320
  if (lastCaptureNs !== undefined && now - lastCaptureNs < nsBetweenSampling) {
321
321
  guardrailMetrics.eventSkipped(
322
322
  SKIPPED_REASON.RATE_LIMIT_PROBE,
323
- isSnapshotProducingProbe === true ? EVENT_TYPE.SNAPSHOT : EVENT_TYPE.LOG
323
+ isSnapshotProducingProbe ? EVENT_TYPE.SNAPSHOT : EVENT_TYPE.LOG
324
324
  )
325
325
  return true
326
326
  }
327
327
 
328
- if (isSnapshotProducingProbe === true &&
328
+ if (isSnapshotProducingProbe &&
329
329
  now - globalSnapshotSamplingRateWindowStart <= oneSecondNs &&
330
330
  snapshotsSampledWithinTheLastSecond >= MAX_SNAPSHOTS_PER_SECOND_GLOBALLY) {
331
331
  guardrailMetrics.eventSkipped(SKIPPED_REASON.RATE_LIMIT_GLOBAL, EVENT_TYPE.SNAPSHOT)
@@ -346,7 +346,7 @@ function installProbeSampler (guardrailMetrics, config) {
346
346
  function commitSample (probeIndex, probeId, now, isSnapshotProducingProbe) {
347
347
  if (!storeSampledProbeIndex(probeIndex)) return false
348
348
 
349
- if (isSnapshotProducingProbe === true) {
349
+ if (isSnapshotProducingProbe) {
350
350
  if (now - globalSnapshotSamplingRateWindowStart > oneSecondNs) {
351
351
  snapshotsSampledWithinTheLastSecond = 1
352
352
  globalSnapshotSamplingRateWindowStart = now
@@ -0,0 +1,16 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Get the name of the runtime if it can't run Live Debugger/Dynamic Instrumentation, or `undefined` if it can.
5
+ *
6
+ * Live Debugger/Dynamic Instrumentation needs the Debugger domain of the `node:inspector` module. Bun only implements a
7
+ * few of its methods, never returns their results, and never emits its events. Deno doesn't let worker threads
8
+ * connect to the main thread inspector. Deno reports a Node.js `process.version`, so both runtimes are detected by
9
+ * their own `process.versions` entry instead.
10
+ */
11
+ function getUnsupportedRuntime () {
12
+ if (process.versions.bun !== undefined) return 'Bun'
13
+ if (process.versions.deno !== undefined) return 'Deno'
14
+ }
15
+
16
+ module.exports = { getUnsupportedRuntime }
@@ -694,7 +694,7 @@ class AgentEncoder {
694
694
  let count = 0
695
695
  for (const key of Object.keys(value)) {
696
696
  const entryValue = value[key]
697
- if (typeof entryValue === 'string' || typeof entryValue === 'number' ||
697
+ if (typeof entryValue === 'string' || typeof entryValue === 'number' || typeof entryValue === 'boolean' ||
698
698
  (entryValue !== null && typeof entryValue === 'object')) {
699
699
  this._encodeString(bytes, key)
700
700
  this.#encodeObjectAsByteArray(bytes, entryValue)
@@ -768,7 +768,7 @@ class AgentEncoder {
768
768
 
769
769
  let count = 0
770
770
  for (const item of value) {
771
- if (typeof item === 'string' || typeof item === 'number' ||
771
+ if (typeof item === 'string' || typeof item === 'number' || typeof item === 'boolean' ||
772
772
  (item !== null && typeof item === 'object' && !circularReferencesDetector.has(item))) {
773
773
  this.#encodeObject(bytes, item, circularReferencesDetector)
774
774
  count++
@@ -0,0 +1,58 @@
1
+ 'use strict'
2
+
3
+ const { MessageChannel } = require('node:worker_threads')
4
+
5
+ const dc = require('dc-polyfill')
6
+
7
+ const moduleLoadStartChannel = dc.channel('dd-trace:moduleLoadStart')
8
+ const moduleLoadEndChannel = dc.channel('dd-trace:moduleLoadEnd')
9
+
10
+ // The loader reports a package once, possibly before dependency telemetry subscribes (the loader handles
11
+ // the whole graph before an app that starts the tracer itself runs), so late consumers replay these.
12
+ /** @type {string[]} */
13
+ const publishedFilenames = []
14
+
15
+ /**
16
+ * Publishes an ESM module load that the loader observed but did not wrap, so consumers such as
17
+ * dependency telemetry see packages without dd-trace instrumentation too.
18
+ *
19
+ * @param {string} filename Loaded module URL.
20
+ */
21
+ function publishModuleLoad (filename) {
22
+ publishedFilenames.push(filename)
23
+ const payload = { filename }
24
+ if (moduleLoadStartChannel.hasSubscribers) {
25
+ moduleLoadStartChannel.publish(payload)
26
+ }
27
+ // Consumers such as datadog-lambda-js cold start tracing pair every start with an end. The load has
28
+ // already happened, so close it right away.
29
+ if (moduleLoadEndChannel.hasSubscribers) {
30
+ moduleLoadEndChannel.publish(payload)
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Returns the ESM module loads published so far, one per package.
36
+ *
37
+ * @returns {string[]}
38
+ */
39
+ function getPublishedModuleLoads () {
40
+ return publishedFilenames
41
+ }
42
+
43
+ /**
44
+ * Builds the `module.register` options that hand the asynchronous loader thread a port to report
45
+ * unwrapped module loads back to the application thread.
46
+ *
47
+ * @returns {{ data: { moduleLoadPort: import('node:worker_threads').MessagePort },
48
+ * transferList: import('node:worker_threads').MessagePort[] }}
49
+ */
50
+ function getLoaderRegisterOptions () {
51
+ const { port1, port2 } = new MessageChannel()
52
+ port1.on('message', publishModuleLoad)
53
+ // The loader thread outlives short-lived applications; never keep them running.
54
+ port1.unref?.()
55
+ return { data: { moduleLoadPort: port2 }, transferList: [port2] }
56
+ }
57
+
58
+ module.exports = { getLoaderRegisterOptions, getPublishedModuleLoads, publishModuleLoad }
@@ -8,6 +8,8 @@ const { isTrue } = require('./util')
8
8
 
9
9
  module.exports = function getExporter (name) {
10
10
  switch (name) {
11
+ case exporters.LLMOBS:
12
+ return usesLambdaLogExporter() ? require('./exporters/log') : require('./exporters/llmobs')
11
13
  case exporters.ELECTRON:
12
14
  return require('./exporters/electron')
13
15
  case exporters.LOG:
@@ -31,12 +33,14 @@ module.exports = function getExporter (name) {
31
33
  return require('./ci-visibility/exporters/test-worker')
32
34
  }
33
35
 
34
- const inAWSLambda = getEnvironmentVariable('AWS_LAMBDA_FUNCTION_NAME') !== undefined
35
- const usingAgent = inAWSLambda && (
36
- fs.existsSync(constants.DATADOG_LAMBDA_EXTENSION_PATH) ||
37
- fs.existsSync(constants.DATADOG_MINI_AGENT_PATH)
38
- )
39
- return inAWSLambda && !usingAgent ? require('./exporters/log') : require('./exporters/agent')
36
+ return usesLambdaLogExporter() ? require('./exporters/log') : require('./exporters/agent')
37
+ }
38
+
39
+ function usesLambdaLogExporter () {
40
+ const { IS_AWS_LAMBDA } = require('./serverless')
41
+ return IS_AWS_LAMBDA &&
42
+ !fs.existsSync(constants.DATADOG_LAMBDA_EXTENSION_PATH) &&
43
+ !fs.existsSync(constants.DATADOG_MINI_AGENT_PATH)
40
44
  }
41
45
 
42
46
  function hasCiValidationEnvironment () {
@@ -44,3 +48,18 @@ function hasCiValidationEnvironment () {
44
48
  getEnvironmentVariable('_DD_TEST_OPTIMIZATION_VALIDATION_MANIFEST_FILE') &&
45
49
  getEnvironmentVariable('_DD_TEST_OPTIMIZATION_VALIDATION_OUTPUT_DIR')
46
50
  }
51
+
52
+ /**
53
+ * Whether the tracer effectively uses OTLP for APM spans.
54
+ * Test Optimization and Electron do not support OTLP even when `OTEL_TRACES_EXPORTER` is `otlp`.
55
+ *
56
+ * @param {import('./config')} config
57
+ */
58
+ function usesOtlpTraceExporter (config) {
59
+ return config.OTEL_TRACES_EXPORTER === 'otlp' &&
60
+ !config.isCiVisibility &&
61
+ config.tracing.DD_TRACE_EXPERIMENTAL_EXPORTER !== exporters.ELECTRON &&
62
+ config.tracing.DD_TRACE_EXPERIMENTAL_EXPORTER !== exporters.AGENTLESS
63
+ }
64
+
65
+ module.exports.usesOtlpTraceExporter = usesOtlpTraceExporter
@@ -44,7 +44,7 @@ class AgentExporter {
44
44
  }
45
45
 
46
46
  export (spans) {
47
- this._writer.append(spans)
47
+ const appended = this._writer.append(spans)
48
48
 
49
49
  const { flushInterval } = this._config
50
50
 
@@ -57,6 +57,8 @@ class AgentExporter {
57
57
  }, flushInterval)
58
58
  this.#timer.unref?.()
59
59
  }
60
+
61
+ return appended
60
62
  }
61
63
 
62
64
  flush (done) {
@@ -86,7 +86,7 @@ class AgentlessExporter {
86
86
  * @param {object[]} spans - Array of spans (all from the same trace)
87
87
  */
88
88
  export (spans) {
89
- this._writer.append(spans)
89
+ const appended = this._writer.append(spans)
90
90
 
91
91
  const { flushInterval } = this.#config
92
92
 
@@ -107,6 +107,8 @@ class AgentlessExporter {
107
107
  }, flushInterval)
108
108
  this.#timer.unref?.()
109
109
  }
110
+
111
+ return appended
110
112
  }
111
113
 
112
114
  /**
@@ -224,10 +224,10 @@ function request (data, options, callback) {
224
224
  isRetriableNetworkError(error)) {
225
225
  settled = true
226
226
  finalize()
227
- // Unref so a pending retry never keeps the host process alive past
228
- // its natural exit point; long-running apps still retry because the
229
- // event loop is held open by their own work.
230
- setTimeout(attempt, getRetryDelay(options, attemptIndex), attemptIndex + 1).unref?.()
227
+ const retryTimer = setTimeout(attempt, getRetryDelay(options, attemptIndex), attemptIndex + 1)
228
+ // Background retries must not keep the host process alive. Lifecycle-owned
229
+ // requests can opt in when their final result must be observed.
230
+ if (!options.keepProcessAlive) retryTimer.unref?.()
231
231
  } else {
232
232
  complete(error)
233
233
  }
@@ -0,0 +1,135 @@
1
+ 'use strict'
2
+
3
+ const { fetchAgentInfo } = require('../../agent/info')
4
+ const { getValueFromEnvSources } = require('../../config/helper')
5
+ const { LLMOBS_META_STRUCT_KEY } = require('../../llmobs/constants/tags')
6
+ const logger = require('../../log')
7
+ const AgentExporter = require('../agent')
8
+ const AgentlessExporter = require('../agentless')
9
+ const BufferingExporter = require('../common/buffering-exporter')
10
+
11
+ const MAX_BUFFERED_SPANS = 1000
12
+
13
+ /**
14
+ * Buffers traces until LLMObs transport discovery selects either the Agent or
15
+ * agentless APM exporter.
16
+ */
17
+ class LLMObsExporter extends BufferingExporter {
18
+ #agentless = false
19
+ #bufferLimitWarned = false
20
+ #bufferedSpanCount = 0
21
+ #exporter
22
+ /** @type {Array<Function | undefined>} */
23
+ #pendingFlushes = []
24
+ #prioritySampler
25
+
26
+ /**
27
+ * @param {import('../../config/config-base')} config
28
+ * @param {import('../../priority_sampler')} prioritySampler
29
+ */
30
+ constructor (config, prioritySampler) {
31
+ super(config)
32
+ this.#prioritySampler = prioritySampler
33
+ this._url = undefined
34
+
35
+ const globalAgentlessEnabled = getValueFromEnvSources('DD_AGENTLESS_ENABLED', true)
36
+
37
+ const exporter = config.tracing.DD_TRACE_EXPERIMENTAL_EXPORTER
38
+ const useAgentlessExporter = exporter === 'agentless' ? true : exporter === 'agent' ? false : undefined
39
+
40
+ const agentlessEnabled = useAgentlessExporter ?? globalAgentlessEnabled ?? config.llmobs.DD_LLMOBS_AGENTLESS_ENABLED
41
+
42
+ if (agentlessEnabled === undefined) {
43
+ fetchAgentInfo(config.url, (err) => {
44
+ this.#initialize(err != null)
45
+ }, { keepProcessAlive: true })
46
+ } else {
47
+ this.#initialize(agentlessEnabled)
48
+ }
49
+ }
50
+
51
+ /**
52
+ *
53
+ * @param {boolean} useAgentless
54
+ */
55
+ #initialize (useAgentless) {
56
+ const Exporter = useAgentless ? AgentlessExporter : AgentExporter
57
+ const pendingUrl = this._url
58
+ this.#agentless = useAgentless
59
+ this.#exporter = new Exporter(this._config, this.#prioritySampler)
60
+ if (pendingUrl !== undefined) this.#exporter.setUrl?.(pendingUrl)
61
+ this._url = this.#exporter._url
62
+
63
+ this._isInitialized = true
64
+ this.exportUncodedTraces()
65
+ this.#bufferedSpanCount = 0
66
+
67
+ const pendingFlushes = this.#pendingFlushes
68
+ this.#pendingFlushes = []
69
+ for (const done of pendingFlushes) this.#exporter.flush(done)
70
+ }
71
+
72
+ /** @param {object[]} trace */
73
+ export (trace) {
74
+ if (!this._isInitialized) {
75
+ if (trace.length > MAX_BUFFERED_SPANS) {
76
+ this.#warnBufferLimit()
77
+ return false
78
+ }
79
+
80
+ if (this.#bufferedSpanCount + trace.length > MAX_BUFFERED_SPANS) this.#warnBufferLimit()
81
+ while (this.#bufferedSpanCount + trace.length > MAX_BUFFERED_SPANS) {
82
+ this.#bufferedSpanCount -= this._traceBuffer.shift().length
83
+ }
84
+
85
+ this._traceBuffer.push(trace)
86
+ this.#bufferedSpanCount += trace.length
87
+ return true
88
+ }
89
+
90
+ if (this.#agentless) this.#normalizeTagKeys(trace)
91
+ return this.#exporter.export(trace)
92
+ }
93
+
94
+ #warnBufferLimit () {
95
+ if (this.#bufferLimitWarned) return
96
+
97
+ this.#bufferLimitWarned = true
98
+ logger.warn('LLMObs exporter trace buffer full (limit is %d spans), dropping trace data', MAX_BUFFERED_SPANS)
99
+ }
100
+
101
+ /** @param {object[]} trace */
102
+ #normalizeTagKeys (trace) {
103
+ for (const span of trace) {
104
+ const llmobs = span.meta_struct?.[LLMOBS_META_STRUCT_KEY]
105
+ if (!llmobs?.tags) continue
106
+
107
+ const tags = {}
108
+ for (const [key, value] of Object.entries(llmobs.tags)) {
109
+ tags[key.replaceAll('.', '_')] = value
110
+ }
111
+ llmobs.tags = tags
112
+ }
113
+ }
114
+
115
+ /** @param {Function} [done] */
116
+ flush (done) {
117
+ if (this._isInitialized) {
118
+ this.#exporter.flush(done)
119
+ } else {
120
+ this.#pendingFlushes.push(done)
121
+ }
122
+ }
123
+
124
+ /** @param {string | URL} url */
125
+ setUrl (url) {
126
+ if (this._isInitialized) {
127
+ this.#exporter.setUrl?.(url)
128
+ this._url = this.#exporter._url
129
+ } else {
130
+ this._url = url
131
+ }
132
+ }
133
+ }
134
+
135
+ module.exports = LLMObsExporter
@@ -16,16 +16,17 @@ class LogExporter {
16
16
 
17
17
  for (const span of spans) {
18
18
  const spanStr = JSON.stringify(span)
19
- if (spanStr.length + TRACE_FORMAT_OVERHEAD > MAX_SIZE) {
19
+ const spanSize = Buffer.byteLength(spanStr, 'utf8')
20
+ if (spanSize + TRACE_FORMAT_OVERHEAD > MAX_SIZE) {
20
21
  log.debug('Span too large to send to logs, dropping')
21
22
  continue
22
23
  }
23
- if (spanStr.length + size > MAX_SIZE) {
24
+ if (spanSize + size > MAX_SIZE) {
24
25
  this._printSpans(queue)
25
26
  queue = []
26
27
  size = TRACE_FORMAT_OVERHEAD
27
28
  }
28
- size += spanStr.length + 1 // includes length of ',' character
29
+ size += spanSize + 1 // includes length of ',' character
29
30
  queue.push(spanStr)
30
31
  }
31
32
  if (queue.length > 0) {
@@ -35,7 +35,7 @@ const LABEL_FIELDS = ['name', 'instructions', 'model']
35
35
  * model_settings?: Record<string, unknown>,
36
36
  * tools?: AgentTool[],
37
37
  * }} AgentManifestFields
38
- * @typedef {{ manifest: AgentManifestFields }} AgentDeclaration
38
+ * @typedef {{ version?: string, manifest?: AgentManifestFields }} AgentDeclaration
39
39
  */
40
40
 
41
41
  /**
@@ -50,8 +50,9 @@ function buildAgentDeclaration (agent) {
50
50
  let declaration
51
51
  try {
52
52
  if (isPlainObject(agent)) {
53
+ const version = toAgentVersion(agent.version)
53
54
  const manifest = buildAgentManifest(agent)
54
- if (manifest !== undefined) declaration = { manifest }
55
+ if (version !== undefined || manifest !== undefined) declaration = { version, manifest }
55
56
  } else {
56
57
  log.warn('Dropping agent annotation, the agent must be a plain object.')
57
58
  }
@@ -105,6 +106,21 @@ function buildAgentManifest (agent) {
105
106
  return manifest
106
107
  }
107
108
 
109
+ /**
110
+ * Unset values (`undefined`, `null`, `''`) are ignored without a warning, so they leave an earlier version in place.
111
+ * A comma is rejected because intake splits tags on it.
112
+ *
113
+ * @param {unknown} version
114
+ */
115
+ function toAgentVersion (version) {
116
+ if (typeof version === 'string' && version !== '') {
117
+ if (!version.includes(',')) return version
118
+ log.warn('Dropping the agent version, it must not contain a comma.')
119
+ return
120
+ }
121
+ if (!isUnset(version)) log.warn('Dropping the agent version, it must be a string.')
122
+ }
123
+
108
124
  /**
109
125
  * @param {unknown} settings
110
126
  * @param {string[]} dropped
@@ -293,4 +309,5 @@ function isScalar (value) {
293
309
  module.exports = {
294
310
  MANUAL_FRAMEWORK_NAME,
295
311
  buildAgentDeclaration,
312
+ toAgentVersion,
296
313
  }
@@ -23,6 +23,8 @@ module.exports = {
23
23
  METADATA: '_ml_obs.meta.metadata',
24
24
  COST_TAGS: '_ml_obs.meta.metadata._dd.cost_tags',
25
25
  AGENT_MANIFEST: '_ml_obs.meta.metadata._dd.agent_manifest',
26
+ AGENT_VERSION: '_ml_obs.agent_version',
27
+ AGENT_VERSION_TAG_KEY: 'agent_version',
26
28
  METRICS: '_ml_obs.metrics',
27
29
  TOOL_DEFINITIONS: '_ml_obs.meta.tool_definitions',
28
30
  ML_APP: '_ml_obs.meta.ml_app',
@@ -33,6 +35,7 @@ module.exports = {
33
35
 
34
36
  PARENT_AGENT_NAME: '_ml_obs.parent_agent_name',
35
37
  PARENT_AGENT_SPAN_ID: '_ml_obs.parent_agent_span_id',
38
+ PARENT_AGENT_VERSION: '_ml_obs.parent_agent_version',
36
39
  PROPAGATED_PARENT_AGENT_ID_KEY: '_dd.p.llmobs_pagent_span_id',
37
40
  PROPAGATED_PARENT_AGENT_NAME_KEY: '_dd.p.llmobs_pagent_name',
38
41
  PROPAGATED_SAMPLE_RATE_KEY: '_dd.p.llmobs_sr',
@@ -48,6 +51,7 @@ module.exports = {
48
51
  LLMOBS_TRACE_ID_BRIDGE_KEY: 'llmobs_trace_id',
49
52
  LLMOBS_PARENT_ID_BRIDGE_KEY: 'llmobs_parent_id',
50
53
  LLMOBS_SUBMITTED_TAG_KEY: '_dd.llmobs.submitted',
54
+ LLMOBS_META_STRUCT_KEY: '_llmobs',
51
55
  ROOT_PARENT_ID: 'undefined',
52
56
  DEFAULT_PROMPT_NAME: 'unnamed-prompt',
53
57
  INTERNAL_CONTEXT_VARIABLE_KEYS: '_dd_context_variable_keys',
@@ -115,7 +115,7 @@ class Experiments {
115
115
  // wait until that many records are readable. Pass `tags` to filter records by
116
116
  // dataset record tags.
117
117
  async pullDataset (name, options = {}) {
118
- const { expectedRecordCount, maxWaitMs = 30_000, projectName, tags, version } = options
118
+ const { expectedRecordCount, maxWaitMs = 30_000, projectName, tags, version: datasetVersion = null } = options
119
119
  const filterTags = validateTagsList(tags)
120
120
  const client = this.#clientForOperation(projectName)
121
121
  const resolvedProjectName = projectName ?? this.#projectName
@@ -123,7 +123,6 @@ class Experiments {
123
123
 
124
124
  let pulledDataset = null
125
125
  let records = []
126
- const datasetVersion = version ?? null
127
126
  let latestVersion = null
128
127
  let lastError = ''
129
128
 
@@ -247,7 +246,7 @@ function createExperiments (config, llmobs) {
247
246
  if (!config.llmobs?.DD_LLMOBS_ENABLED) {
248
247
  return new NoopExperiments('LLM Observability is not enabled')
249
248
  }
250
- if (!(config.DD_API_KEY) || !config.DD_APP_KEY) {
249
+ if (config.DD_API_KEY === undefined || config.DD_APP_KEY === undefined) {
251
250
  log.warn('LLMObs experiments: missing api and/or app keys, set DD_API_KEY and DD_APP_KEY')
252
251
  return new NoopExperiments('DD_API_KEY and DD_APP_KEY are required for experiments')
253
252
  }
@@ -256,8 +256,11 @@ class NoopExperiment {
256
256
  class NoopExperiments {
257
257
  #reason
258
258
 
259
- constructor (reason) {
260
- this.#reason = reason || 'LLMObs experiments are not available'
259
+ /**
260
+ * @param {string} [reason]
261
+ */
262
+ constructor (reason = 'LLMObs experiments are not available') {
263
+ this.#reason = reason
261
264
  }
262
265
 
263
266
  #warn () {