dd-trace 6.24.0 → 6.26.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 (352) hide show
  1. package/README.md +3 -0
  2. package/ci/cypress/support.js +2 -1
  3. package/ci/init.js +2 -22
  4. package/ci/vitest-no-worker-init-node-setup.mjs +2 -1
  5. package/ci/vitest-no-worker-init-runner-setup.mjs +2 -1
  6. package/ci/vitest-no-worker-init-setup.mjs +729 -724
  7. package/ci/vitest-no-worker-init-v5-setup.mjs +2 -1
  8. package/ext/exporters.js +0 -1
  9. package/index.d.ts +105 -5
  10. package/initialize.mjs +5 -2
  11. package/package.json +41 -36
  12. package/packages/datadog-esbuild/index.js +16 -70
  13. package/packages/datadog-esbuild/src/log.js +2 -29
  14. package/packages/datadog-instrumentations/src/ai.js +6 -1
  15. package/packages/datadog-instrumentations/src/aws-lambda.js +88 -0
  16. package/packages/datadog-instrumentations/src/cucumber.js +5 -2
  17. package/packages/datadog-instrumentations/src/cypress-config.js +20 -9
  18. package/packages/datadog-instrumentations/src/elevenlabs/activity.js +114 -0
  19. package/packages/datadog-instrumentations/src/elevenlabs/audio.js +104 -0
  20. package/packages/datadog-instrumentations/src/elevenlabs/index.js +288 -0
  21. package/packages/datadog-instrumentations/src/elevenlabs/session.js +444 -0
  22. package/packages/datadog-instrumentations/src/graphql.js +20 -17
  23. package/packages/datadog-instrumentations/src/helpers/bundler-esm-exports.js +582 -0
  24. package/packages/datadog-instrumentations/src/helpers/bundler-log.js +38 -0
  25. package/packages/datadog-instrumentations/src/helpers/bundler-transform.js +576 -0
  26. package/packages/datadog-instrumentations/src/helpers/bundler-utils.js +104 -0
  27. package/packages/datadog-instrumentations/src/helpers/fetch.js +51 -6
  28. package/packages/datadog-instrumentations/src/helpers/hook.js +29 -1
  29. package/packages/datadog-instrumentations/src/helpers/hooks.js +3 -7
  30. package/packages/datadog-instrumentations/src/helpers/lambda-handler.js +189 -0
  31. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +8 -0
  32. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +26 -1
  33. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/async-mutex.js +41 -0
  34. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/elevenlabs.js +25 -0
  35. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql.js +0 -36
  36. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-client.js +30 -0
  37. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-server.js +23 -0
  38. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/next.js +61 -0
  39. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/openai-agents-realtime.js +23 -0
  40. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/postgres.js +33 -4
  41. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/trpc.js +148 -0
  42. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +80 -0
  43. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +23 -3
  44. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms/postgres.js +122 -0
  45. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +59 -2
  46. package/packages/datadog-instrumentations/src/ioredis.js +101 -3
  47. package/packages/datadog-instrumentations/src/microgateway-core.js +1 -2
  48. package/packages/datadog-instrumentations/src/modelcontextprotocol-client.js +21 -0
  49. package/packages/datadog-instrumentations/src/modelcontextprotocol-sdk.js +7 -1
  50. package/packages/datadog-instrumentations/src/modelcontextprotocol-server.js +41 -0
  51. package/packages/datadog-instrumentations/src/next.js +203 -26
  52. package/packages/datadog-instrumentations/src/openai-agents-realtime.js +149 -0
  53. package/packages/datadog-instrumentations/src/openai-realtime/audio-accumulator.js +27 -0
  54. package/packages/datadog-instrumentations/src/openai-realtime/index.js +17 -6
  55. package/packages/datadog-instrumentations/src/openai-realtime/server-playback.js +887 -0
  56. package/packages/datadog-instrumentations/src/openai-realtime/session.js +150 -25
  57. package/packages/datadog-instrumentations/src/openai-realtime/turns.js +29 -2
  58. package/packages/datadog-instrumentations/src/otel-sdk-trace.js +11 -9
  59. package/packages/datadog-instrumentations/src/router.js +35 -12
  60. package/packages/datadog-instrumentations/src/vitest-main.js +10 -2
  61. package/packages/datadog-instrumentations/src/webdriverio.js +12 -12
  62. package/packages/datadog-plugin-async-mutex/src/index.js +50 -0
  63. package/packages/datadog-plugin-aws-lambda/src/arn.js +41 -0
  64. package/packages/datadog-plugin-aws-lambda/src/event-type-guards.js +170 -0
  65. package/packages/datadog-plugin-aws-lambda/src/index.js +106 -0
  66. package/packages/datadog-plugin-aws-lambda/src/trigger.js +339 -0
  67. package/packages/datadog-plugin-aws-sdk/src/services/dynamodb.js +7 -0
  68. package/packages/datadog-plugin-aws-sdk/src/services/kinesis.js +32 -10
  69. package/packages/datadog-plugin-aws-sdk/src/services/lambda.js +10 -1
  70. package/packages/datadog-plugin-aws-sdk/src/services/sqs.js +4 -0
  71. package/packages/datadog-plugin-aws-sdk/src/services/stepfunctions.js +3 -0
  72. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +50 -13
  73. package/packages/datadog-plugin-cypress/src/support.mjs +1353 -0
  74. package/packages/datadog-plugin-elevenlabs/src/index.js +69 -0
  75. package/packages/datadog-plugin-express/src/code_origin.js +2 -2
  76. package/packages/datadog-plugin-fastify/src/code_origin.js +2 -2
  77. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +20 -7
  78. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +21 -52
  79. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +11 -2
  80. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-request-context.js +25 -4
  81. package/packages/datadog-plugin-google-cloud-pubsub/src/resource-names.js +24 -0
  82. package/packages/datadog-plugin-graphql/src/tools/transforms.js +1 -0
  83. package/packages/datadog-plugin-http/src/client.js +34 -10
  84. package/packages/datadog-plugin-http2/src/client.js +40 -14
  85. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/tracing.js +28 -2
  86. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/utils.js +1 -0
  87. package/packages/datadog-plugin-mongodb-core/src/query.js +17 -1
  88. package/packages/datadog-plugin-next/src/index.js +112 -14
  89. package/packages/datadog-plugin-postgres/src/index.js +118 -41
  90. package/packages/datadog-plugin-prisma/src/datadog-tracing-helper.js +5 -3
  91. package/packages/datadog-plugin-supabase/src/supabase-auth-js-gotrueclient-getuser.js +18 -8
  92. package/packages/datadog-plugin-supabase/src/supabase-functions-js-functionsclient-invoke.js +49 -13
  93. package/packages/datadog-plugin-supabase/src/supabase-storage-js-handle-request.js +34 -9
  94. package/packages/datadog-plugin-trpc/src/index.js +15 -0
  95. package/packages/datadog-plugin-trpc/src/procedure.js +48 -0
  96. package/packages/datadog-plugin-trpc/src/request.js +81 -0
  97. package/packages/datadog-plugin-undici/src/index.js +22 -7
  98. package/packages/datadog-plugin-vitest/src/index.js +3 -2
  99. package/packages/datadog-plugin-ws/src/close.js +3 -5
  100. package/packages/datadog-plugin-ws/src/producer.js +1 -4
  101. package/packages/datadog-plugin-ws/src/receiver.js +3 -5
  102. package/packages/datadog-plugin-ws/src/server.js +44 -13
  103. package/packages/datadog-turbopack/index.js +4 -28
  104. package/packages/datadog-turbopack/src/loader.js +14 -452
  105. package/packages/datadog-vite/index.js +537 -0
  106. package/packages/datadog-vite/src/log.js +5 -0
  107. package/packages/datadog-webpack/index.js +3 -55
  108. package/packages/datadog-webpack/src/log.js +2 -29
  109. package/packages/dd-trace/src/aiguard/evaluation.js +62 -1
  110. package/packages/dd-trace/src/aiguard/index.js +1 -1
  111. package/packages/dd-trace/src/aiguard/integrations/index.js +6 -5
  112. package/packages/dd-trace/src/aiguard/sdk.js +8 -2
  113. package/packages/dd-trace/src/aiguard/tags.js +2 -0
  114. package/packages/dd-trace/src/appsec/blocking/index.js +21 -1
  115. package/packages/dd-trace/src/appsec/channels.js +7 -0
  116. package/packages/dd-trace/src/appsec/downstream_requests.js +105 -0
  117. package/packages/dd-trace/src/appsec/graphql.js +89 -7
  118. package/packages/dd-trace/src/appsec/handlers/auth.js +1 -3
  119. package/packages/dd-trace/src/appsec/handlers/http-request.js +60 -65
  120. package/packages/dd-trace/src/appsec/handlers/http-response.js +61 -7
  121. package/packages/dd-trace/src/appsec/handlers/payments.js +23 -27
  122. package/packages/dd-trace/src/appsec/index.js +6 -0
  123. package/packages/dd-trace/src/appsec/lambda.js +17 -17
  124. package/packages/dd-trace/src/appsec/rasp/command_injection.js +4 -4
  125. package/packages/dd-trace/src/appsec/rasp/index.js +8 -1
  126. package/packages/dd-trace/src/appsec/rasp/lfi.js +2 -2
  127. package/packages/dd-trace/src/appsec/rasp/sql_injection.js +7 -17
  128. package/packages/dd-trace/src/appsec/rasp/ssrf.js +80 -16
  129. package/packages/dd-trace/src/appsec/rasp/utils.js +33 -3
  130. package/packages/dd-trace/src/appsec/recommended.json +1358 -94
  131. package/packages/dd-trace/src/appsec/reporter.js +9 -0
  132. package/packages/dd-trace/src/appsec/sdk/set_user.js +3 -3
  133. package/packages/dd-trace/src/appsec/sdk/track_event.js +4 -4
  134. package/packages/dd-trace/src/appsec/sdk/user_blocking.js +1 -1
  135. package/packages/dd-trace/src/appsec/user_tracking.js +6 -8
  136. package/packages/dd-trace/src/appsec/waf/index.js +65 -6
  137. package/packages/dd-trace/src/appsec/waf/waf_context_wrapper.js +33 -38
  138. package/packages/dd-trace/src/appsec/waf/waf_manager.js +18 -2
  139. package/packages/dd-trace/src/before-exit.js +32 -0
  140. package/packages/dd-trace/src/bootstrap.js +5 -3
  141. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +15 -2
  142. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +12 -34
  143. package/packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js +41 -13
  144. package/packages/dd-trace/src/ci-visibility/exporters/request.js +2 -3
  145. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +1 -2
  146. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +1 -1
  147. package/packages/dd-trace/src/ci-visibility/telemetry.js +6 -0
  148. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +1 -1
  149. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache-schema.js +9 -134
  150. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache.js +11 -156
  151. package/packages/dd-trace/src/config/config-types.d.ts +3 -0
  152. package/packages/dd-trace/src/config/defaults.js +5 -0
  153. package/packages/dd-trace/src/config/generated-config-types.d.ts +46 -4
  154. package/packages/dd-trace/src/config/index.js +63 -31
  155. package/packages/dd-trace/src/config/parsers.js +44 -0
  156. package/packages/dd-trace/src/config/remote-config-layers.js +38 -0
  157. package/packages/dd-trace/src/config/remote_config.js +2 -1
  158. package/packages/dd-trace/src/config/supported-configurations.json +172 -10
  159. package/packages/dd-trace/src/constants.js +1 -0
  160. package/packages/dd-trace/src/datastreams/fnv.js +27 -0
  161. package/packages/dd-trace/src/datastreams/pathway.js +113 -28
  162. package/packages/dd-trace/src/datastreams/processor.js +5 -4
  163. package/packages/dd-trace/src/debugger/config.js +1 -1
  164. package/packages/dd-trace/src/debugger/devtools_client/request-options.js +7 -9
  165. package/packages/dd-trace/src/debugger/devtools_client/send.js +1 -1
  166. package/packages/dd-trace/src/debugger/devtools_client/state.js +3 -1
  167. package/packages/dd-trace/src/debugger/devtools_client/tags.js +1 -1
  168. package/packages/dd-trace/src/debugger/index.js +2 -2
  169. package/packages/dd-trace/src/debugger/inspect-segment.js +3 -2
  170. package/packages/dd-trace/src/debugger/pause-duration-histogram.js +6 -2
  171. package/packages/dd-trace/src/debugger/probe_sampler.js +39 -17
  172. package/packages/dd-trace/src/debugger/unsupported-runtime.js +2 -0
  173. package/packages/dd-trace/src/exporter.js +0 -11
  174. package/packages/dd-trace/src/exporters/common/request.js +81 -48
  175. package/packages/dd-trace/src/exporters/common/retry.js +12 -7
  176. package/packages/dd-trace/src/exporters/common/url.js +1 -1
  177. package/packages/dd-trace/src/git_metadata.js +2 -1
  178. package/packages/dd-trace/src/id.js +1 -1
  179. package/packages/dd-trace/src/index.js +6 -3
  180. package/packages/dd-trace/src/lambda/facade.js +75 -0
  181. package/packages/dd-trace/src/lambda/handler.js +3 -41
  182. package/packages/dd-trace/src/lambda/index.js +38 -15
  183. package/packages/dd-trace/src/lambda/runtime/patch.js +19 -3
  184. package/packages/dd-trace/src/lambda/wrap.js +44 -0
  185. package/packages/dd-trace/src/llmobs/constants/tags.js +2 -0
  186. package/packages/dd-trace/src/llmobs/experiments/experiment.js +10 -5
  187. package/packages/dd-trace/src/llmobs/plugins/elevenlabs.js +96 -0
  188. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +19 -6
  189. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/index.js +54 -3
  190. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/utils.js +81 -1
  191. package/packages/dd-trace/src/llmobs/plugins/openai/realtime.js +38 -11
  192. package/packages/dd-trace/src/llmobs/plugins/vertexai.js +10 -2
  193. package/packages/dd-trace/src/llmobs/sdk.js +19 -0
  194. package/packages/dd-trace/src/llmobs/span_processor.js +9 -0
  195. package/packages/dd-trace/src/llmobs/tagger.js +22 -0
  196. package/packages/dd-trace/src/log/channels.js +4 -0
  197. package/packages/dd-trace/src/log/writer.js +6 -1
  198. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +7 -0
  199. package/packages/dd-trace/src/openfeature/configuration_source.js +55 -27
  200. package/packages/dd-trace/src/openfeature/flag-selection.js +152 -0
  201. package/packages/dd-trace/src/openfeature/flagging_provider.js +19 -1
  202. package/packages/dd-trace/src/openfeature/writers/base.js +1 -3
  203. package/packages/dd-trace/src/opentelemetry/logs/index.js +11 -0
  204. package/packages/dd-trace/src/opentelemetry/logs/otlp_http_log_exporter.js +1 -1
  205. package/packages/dd-trace/src/opentelemetry/metrics/index.js +7 -1
  206. package/packages/dd-trace/src/opentelemetry/metrics/otlp_http_metric_exporter.js +1 -1
  207. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_exporter.js +4 -1
  208. package/packages/dd-trace/src/opentelemetry/otlp/otlp_http_exporter_base.js +19 -1
  209. package/packages/dd-trace/src/opentelemetry/span-ending-hook.js +5 -1
  210. package/packages/dd-trace/src/opentelemetry/span-helpers.js +6 -1
  211. package/packages/dd-trace/src/opentelemetry/span.js +2 -2
  212. package/packages/dd-trace/src/opentelemetry/startup-config.js +174 -0
  213. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +1 -1
  214. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +7 -1
  215. package/packages/dd-trace/src/opentracing/propagation/tracestate.js +77 -23
  216. package/packages/dd-trace/src/opentracing/tracer.js +24 -0
  217. package/packages/dd-trace/src/otel-thread-ctx.js +28 -31
  218. package/packages/dd-trace/src/plugin_manager.js +34 -7
  219. package/packages/dd-trace/src/plugins/ci_plugin.js +143 -17
  220. package/packages/dd-trace/src/plugins/index.js +8 -0
  221. package/packages/dd-trace/src/plugins/plugin.js +4 -2
  222. package/packages/dd-trace/src/plugins/tracing.js +1 -1
  223. package/packages/dd-trace/src/plugins/util/ci.js +52 -1
  224. package/packages/dd-trace/src/plugins/util/git-cache.js +4 -4
  225. package/packages/dd-trace/src/plugins/util/git.js +263 -82
  226. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +80 -56
  227. package/packages/dd-trace/src/plugins/util/inferred_proxy.js +12 -4
  228. package/packages/dd-trace/src/plugins/util/status-validator.js +23 -10
  229. package/packages/dd-trace/src/plugins/util/tags.js +6 -0
  230. package/packages/dd-trace/src/plugins/util/test.js +92 -40
  231. package/packages/dd-trace/src/plugins/util/url.js +18 -7
  232. package/packages/dd-trace/src/plugins/util/user-provided-git.js +6 -6
  233. package/packages/dd-trace/src/plugins/util/web.js +65 -10
  234. package/packages/dd-trace/src/process-tags/index.js +1 -1
  235. package/packages/dd-trace/src/profiler.js +74 -12
  236. package/packages/dd-trace/src/profiling/profiler.js +30 -2
  237. package/packages/dd-trace/src/profiling/profilers/space.js +3 -1
  238. package/packages/dd-trace/src/profiling/profilers/wall.js +4 -4
  239. package/packages/dd-trace/src/profiling/remote-config.js +354 -0
  240. package/packages/dd-trace/src/profiling/runtime-capabilities.js +11 -0
  241. package/packages/dd-trace/src/profiling/webspan-utils.js +6 -5
  242. package/packages/dd-trace/src/propagation-hash/index.js +7 -0
  243. package/packages/dd-trace/src/proxy.js +46 -54
  244. package/packages/dd-trace/src/span_processor.js +20 -0
  245. package/packages/dd-trace/src/startup-log.js +8 -6
  246. package/packages/dd-trace/src/telemetry/metrics.js +2 -1
  247. package/packages/dd-trace/src/tracer.js +0 -2
  248. package/packages/dd-trace/src/web-tags-cache.js +8 -9
  249. package/register.js +2 -1
  250. package/vendor/dist/@apm-js-collab/code-transformer/LICENSE +489 -0
  251. package/vendor/dist/@datadog/flagging-core/LICENSE +221 -0
  252. package/vendor/dist/@datadog/flagging-core/index.js +1 -0
  253. package/vendor/dist/@datadog/openfeature-node-server/LICENSE +21 -1
  254. package/vendor/dist/@datadog/openfeature-node-server/rules-based/LICENSE +3 -1
  255. package/vendor/dist/@datadog/sketches-js/LICENSE +263 -0
  256. package/vendor/dist/@datadog/source-map/LICENSE +1 -0
  257. package/vendor/dist/@isaacs/ttlcache/LICENSE +13 -0
  258. package/vendor/dist/@opentelemetry/core/LICENSE +220 -1
  259. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  260. package/vendor/dist/crypto-randomuuid/LICENSE +3 -0
  261. package/vendor/dist/escape-string-regexp/LICENSE +13 -0
  262. package/vendor/dist/esquery/LICENSE +2 -0
  263. package/vendor/dist/https-proxy-agent/LICENSE +80 -1
  264. package/vendor/dist/istanbul-lib-coverage/LICENSE +2 -0
  265. package/vendor/dist/jest-docblock/LICENSE +16 -0
  266. package/vendor/dist/jsonpath-plus/LICENSE +13 -0
  267. package/vendor/dist/limiter/LICENSE +2 -0
  268. package/vendor/dist/lodash.sortby/LICENSE +2 -0
  269. package/vendor/dist/lru-cache/LICENSE +13 -0
  270. package/vendor/dist/meriyah/LICENSE +13 -0
  271. package/vendor/dist/module-details-from-path/LICENSE +2 -0
  272. package/vendor/dist/mutexify/promise/LICENSE +28 -0
  273. package/vendor/dist/pprof-format/LICENSE +13 -0
  274. package/vendor/dist/pprof-format/index.js +1 -1
  275. package/vendor/dist/protobufjs/LICENSE +219 -0
  276. package/vendor/dist/protobufjs/minimal/LICENSE +219 -0
  277. package/vendor/dist/proxy-from-env/LICENSE +13 -0
  278. package/vendor/dist/retry/LICENSE +2 -0
  279. package/vendor/dist/rfdc/LICENSE +2 -0
  280. package/vendor/dist/semifies/LICENSE +3 -1
  281. package/vendor/dist/shell-quote/LICENSE +3 -1
  282. package/vendor/dist/source-map/LICENSE +1 -0
  283. package/vendor/dist/source-map/lib/util/LICENSE +1 -0
  284. package/vendor/dist/tlhunter-sorted-set/LICENSE +2 -0
  285. package/vendor/dist/ttl-set/LICENSE +28 -0
  286. package/vite.d.ts +7 -0
  287. package/vite.js +3 -0
  288. package/ci/diagnose.js +0 -2215
  289. package/ci/runbook.md +0 -299
  290. package/ci/test-optimization-validation/approval-artifacts.js +0 -175
  291. package/ci/test-optimization-validation/approval.js +0 -386
  292. package/ci/test-optimization-validation/artifact-id.js +0 -18
  293. package/ci/test-optimization-validation/blocker-category.js +0 -24
  294. package/ci/test-optimization-validation/bounded-json.js +0 -120
  295. package/ci/test-optimization-validation/ci-command-candidate.js +0 -77
  296. package/ci/test-optimization-validation/ci-discovery.js +0 -192
  297. package/ci/test-optimization-validation/ci-package-scripts.js +0 -169
  298. package/ci/test-optimization-validation/ci-remediation.js +0 -283
  299. package/ci/test-optimization-validation/cli.js +0 -954
  300. package/ci/test-optimization-validation/command-blocker.js +0 -377
  301. package/ci/test-optimization-validation/command-output-policy.js +0 -188
  302. package/ci/test-optimization-validation/command-runner.js +0 -649
  303. package/ci/test-optimization-validation/environment.js +0 -88
  304. package/ci/test-optimization-validation/executable-approval.js +0 -47
  305. package/ci/test-optimization-validation/executable.js +0 -244
  306. package/ci/test-optimization-validation/execution-lock.js +0 -70
  307. package/ci/test-optimization-validation/framework-adapters/cucumber-validation.json +0 -3
  308. package/ci/test-optimization-validation/framework-adapters/cucumber.js +0 -767
  309. package/ci/test-optimization-validation/framework-adapters/cypress.js +0 -99
  310. package/ci/test-optimization-validation/framework-adapters/playwright.js +0 -175
  311. package/ci/test-optimization-validation/framework-adapters/vitest.js +0 -513
  312. package/ci/test-optimization-validation/generated-file-policy.js +0 -63
  313. package/ci/test-optimization-validation/generated-files.js +0 -425
  314. package/ci/test-optimization-validation/generated-test-contract.js +0 -284
  315. package/ci/test-optimization-validation/generated-verifier.js +0 -235
  316. package/ci/test-optimization-validation/literal-environment.js +0 -56
  317. package/ci/test-optimization-validation/literal-glob.js +0 -52
  318. package/ci/test-optimization-validation/manifest-loader.js +0 -116
  319. package/ci/test-optimization-validation/manifest-scaffold.js +0 -1276
  320. package/ci/test-optimization-validation/manifest-schema.js +0 -695
  321. package/ci/test-optimization-validation/offline-fixtures.js +0 -335
  322. package/ci/test-optimization-validation/offline-output.js +0 -406
  323. package/ci/test-optimization-validation/package-check.js +0 -97
  324. package/ci/test-optimization-validation/payload-normalizer.js +0 -72
  325. package/ci/test-optimization-validation/plan-writer.js +0 -541
  326. package/ci/test-optimization-validation/preflight-runner.js +0 -186
  327. package/ci/test-optimization-validation/project-build-artifact.js +0 -31
  328. package/ci/test-optimization-validation/redaction.js +0 -319
  329. package/ci/test-optimization-validation/report-writer.js +0 -666
  330. package/ci/test-optimization-validation/result-semantics.js +0 -103
  331. package/ci/test-optimization-validation/runner-command.js +0 -264
  332. package/ci/test-optimization-validation/runner-contract.js +0 -695
  333. package/ci/test-optimization-validation/safe-files.js +0 -202
  334. package/ci/test-optimization-validation/scenarios/auto-test-retries.js +0 -171
  335. package/ci/test-optimization-validation/scenarios/basic-reporting.js +0 -407
  336. package/ci/test-optimization-validation/scenarios/ci-wiring.js +0 -666
  337. package/ci/test-optimization-validation/scenarios/early-flake-detection.js +0 -142
  338. package/ci/test-optimization-validation/scenarios/helpers.js +0 -621
  339. package/ci/test-optimization-validation/scenarios/test-management.js +0 -219
  340. package/ci/test-optimization-validation/source-text.js +0 -84
  341. package/ci/test-optimization-validation/static-diagnosis.js +0 -166
  342. package/ci/test-optimization-validation/test-output.js +0 -120
  343. package/ci/test-optimization-validation/validation-blocker.js +0 -21
  344. package/ci/validate-test-optimization.js +0 -3
  345. package/packages/datadog-esbuild/src/resolver.js +0 -284
  346. package/packages/datadog-esbuild/src/utils.js +0 -318
  347. package/packages/datadog-plugin-cypress/src/support.js +0 -1348
  348. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/index.js +0 -156
  349. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/msgpack-to-json.js +0 -287
  350. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/payload-projection.js +0 -84
  351. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/sink.js +0 -368
  352. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/writer.js +0 -59
@@ -10,6 +10,7 @@ const {
10
10
  const log = require('../../../dd-trace/src/log')
11
11
  const { extractResponseTools, normalizeResponseEventType } = require('./events')
12
12
  const { InputTurn, ResponseTurn } = require('./turns')
13
+ const ServerPlayback = require('./server-playback')
13
14
 
14
15
  // Realtime PCM is 24 kHz mono by spec; overridden from the session's format object when present.
15
16
  const DEFAULT_AUDIO_RATE = 24_000
@@ -212,6 +213,10 @@ class RealtimeSession {
212
213
  */
213
214
  #clientTruncates = false
214
215
 
216
+ #playback
217
+
218
+ #vadSilenceMs = 0
219
+
215
220
  #closed = false
216
221
 
217
222
  /**
@@ -221,14 +226,41 @@ class RealtimeSession {
221
226
  * @param {string} [options.model]
222
227
  * @param {string} [options.basePath]
223
228
  * @param {() => boolean} [options.shouldRetainAudio]
229
+ * @param {string} [options.sessionId]
230
+ * @param {boolean} [options.serverPlayback]
231
+ * @param {(itemId: string, eventId: string) => void} [options.requestItem]
224
232
  */
225
- constructor ({ emitTurn, captureContext, model, basePath = '', shouldRetainAudio = () => true }) {
233
+ constructor ({
234
+ emitTurn, captureContext, model, basePath = '', shouldRetainAudio = () => true,
235
+ sessionId, serverPlayback = false, requestItem,
236
+ }) {
226
237
  this.#emitTurn = emitTurn
227
238
  this.#captureContext = captureContext
228
239
  this.#model = model
229
240
  this.#basePath = basePath
230
241
  this.#shouldRetainAudio = shouldRetainAudio
231
242
  this.#pendingInput = new InputTurn(shouldRetainAudio)
243
+ if (sessionId) this.#sessionId = sessionId
244
+ if (serverPlayback) {
245
+ this.#playback = new ServerPlayback({
246
+ shouldRetainAudio,
247
+ requestItem,
248
+ onTranscript: (itemId, text, now) => this.#onInputTranscript(itemId, text, now),
249
+ onReady: (turn, now) => {
250
+ for (const [id, candidate] of this.#responses) {
251
+ if (candidate === turn) this.#responses.delete(id)
252
+ }
253
+ const index = this.#awaiting.indexOf(turn)
254
+ if (index !== -1) this.#awaiting.splice(index, 1)
255
+ this.#finalizeTurn(turn, now, true)
256
+ },
257
+ })
258
+ }
259
+ }
260
+
261
+ /** @param {{ type?: string, error?: { event_id?: unknown } } | undefined} event */
262
+ isRetrievalError (event) {
263
+ return this.#playback?.isRetrievalError(event) ?? false
232
264
  }
233
265
 
234
266
  // -- event entry points ---------------------------------------------------
@@ -240,6 +272,7 @@ class RealtimeSession {
240
272
  onClientEvent (event, now) {
241
273
  try {
242
274
  this.#flushPlaying(now)
275
+ this.#playback?.onClientEvent(event)
243
276
 
244
277
  switch (event?.type) {
245
278
  // First: a server-VAD client appends microphone audio many times a second.
@@ -276,6 +309,7 @@ class RealtimeSession {
276
309
 
277
310
  const eventType = event?.type
278
311
  if (typeof eventType !== 'string') return
312
+ this.#playback?.onServerEvent(event, now)
279
313
 
280
314
  switch (eventType) {
281
315
  case 'session.created':
@@ -288,18 +322,25 @@ class RealtimeSession {
288
322
  this.#onTruncate(event.item_id, event.audio_end_ms, now)
289
323
  return
290
324
  case 'input_audio_buffer.speech_started':
291
- this.#onSpeechStarted(event.audio_start_ms, now)
325
+ this.#onSpeechStarted(event.audio_start_ms, now, event.item_id)
292
326
  return
293
327
  case 'input_audio_buffer.speech_stopped':
294
- // The commit that follows is the authoritative end of user speech and overwrites this;
295
- // recording it here only covers a session that never commits, so the window still gets an
296
- // end.
297
- this.#pendingInput.speechEndTime ??= now
328
+ this.#onSpeechStopped(event.audio_end_ms, now, event.item_id)
298
329
  return
299
- case 'input_audio_buffer.committed':
300
- this.#pendingInput.itemId = event.item_id == null ? undefined : String(event.item_id)
301
- this.#pendingInput.speechEndTime = now
330
+ case 'input_audio_buffer.committed': {
331
+ const pending = this.#pendingInput
332
+ const itemId = event.item_id == null ? undefined : String(event.item_id)
333
+ if (this.#playback && pending.itemId !== undefined && pending.itemId !== itemId) {
334
+ this.#resetPendingSpeech()
335
+ }
336
+ if (pending.itemId !== itemId) this.#inputTranscripts.delete(pending.itemId)
337
+ pending.itemId = itemId
338
+ if (this.#playback) pending.speechItemId = itemId
339
+ this.#playback?.rememberInput(pending, this.#inputTranscriptionEnabled &&
340
+ itemId !== undefined && !this.#inputTranscripts.has(itemId))
341
+ if (!this.#playback || pending.speechEndTime === undefined) pending.speechEndTime = now
302
342
  return
343
+ }
303
344
  case 'input_audio_buffer.cleared':
304
345
  this.#pendingInput.discardAudio()
305
346
  return
@@ -352,6 +393,7 @@ class RealtimeSession {
352
393
  }
353
394
 
354
395
  this.#responses.clear()
396
+ this.#playback?.finishSession(now)
355
397
  this.#inputTranscripts.clear()
356
398
  this.#toolCallNames.clear()
357
399
  // Audio buffered for a turn that will now never start. An app that holds on to closed
@@ -460,18 +502,29 @@ class RealtimeSession {
460
502
  * keeping, so the buffered lead-in is trimmed off the front to keep the captured audio and the
461
503
  * reported window in step.
462
504
  *
463
- * Only the first onset of a turn counts: a turn that VAD splits into several speech runs before a
464
- * single commit is still one committed item, which began at the first run.
505
+ * Repeated onsets for the same item keep its first boundary. A new item retires the previous
506
+ * committed clip, even when automatic response creation is disabled.
465
507
  *
466
508
  * @param {unknown} audioStartMs
467
509
  * @param {number} now
510
+ * @param {unknown} itemId
468
511
  */
469
- #onSpeechStarted (audioStartMs, now) {
512
+ #onSpeechStarted (audioStartMs, now, itemId) {
470
513
  const pending = this.#pendingInput
514
+ if (this.#playback) {
515
+ const item = itemId == null ? undefined : String(itemId)
516
+ const current = pending.speechItemId ?? pending.itemId
517
+ if (current !== undefined && item !== current) this.#resetPendingSpeech()
518
+ pending.speechItemId = item
519
+ }
471
520
  if (pending.speechStartTime !== undefined) return
472
521
 
473
522
  const onset = this.#bufferOffsetToWallTime(audioStartMs, now)
474
523
  pending.speechStartTime = onset
524
+ const startOffset = toFiniteNumber(audioStartMs)
525
+ if (this.#playback && startOffset !== undefined && startOffset >= 0) {
526
+ pending.speechStartOffsetMs = startOffset
527
+ }
475
528
 
476
529
  pending.audio.trimLeading(this.#preOnsetBytes(audioStartMs))
477
530
  // Re-anchor the segment on the onset: whatever survived the trim starts there. A trim that
@@ -482,6 +535,51 @@ class RealtimeSession {
482
535
  if (pending.audio.startTime !== undefined) pending.audio.startTime = onset
483
536
  }
484
537
 
538
+ /**
539
+ * End a VAD window. A sideband observes no input frames, so its start event's
540
+ * arrival cannot anchor the stored clip: that clip includes pre-detection audio.
541
+ * Project the protocol's start/end offsets back from the stop observation instead.
542
+ *
543
+ * @param {unknown} audioEndMs
544
+ * @param {number} now
545
+ * @param {unknown} itemId
546
+ */
547
+ #onSpeechStopped (audioEndMs, now, itemId) {
548
+ const pending = this.#pendingInput
549
+ if (this.#playback) {
550
+ const item = itemId == null ? undefined : String(itemId)
551
+ const current = pending.speechItemId ?? pending.itemId
552
+ if (item !== undefined && current !== undefined && item !== current) return
553
+ const endMs = toFiniteNumber(audioEndMs)
554
+ if (pending.speechEndTime !== undefined &&
555
+ (endMs === undefined || endMs < 0 || endMs <= (pending.speechEndOffsetMs ?? -1))) return
556
+ const firstStop = pending.speechEndOffsetMs === undefined
557
+ pending.speechItemId ??= item
558
+ if (endMs !== undefined && endMs >= 0) pending.speechEndOffsetMs = endMs
559
+ const startMs = pending.speechStartOffsetMs
560
+ if (firstStop && startMs !== undefined && endMs !== undefined && endMs >= startMs &&
561
+ pending.speechStartTime !== undefined) {
562
+ // AIDEV-NOTE: both offsets include VAD padding. Removing silence from the
563
+ // duration as well would shift the caller forward and erase barge-in overlap.
564
+ pending.speechStartTime = Math.min(pending.speechStartTime, Math.max(0, now - (endMs - startMs)))
565
+ }
566
+ pending.speechEndTime = Math.max(pending.speechEndTime ?? 0,
567
+ pending.speechStartTime ?? 0, now - this.#vadSilenceMs)
568
+ } else {
569
+ // Existing WebSocket clients anchor the start from their observed input frames;
570
+ // the subsequent commit remains their authoritative speech end.
571
+ pending.speechEndTime ??= now
572
+ }
573
+ }
574
+
575
+ #resetPendingSpeech () {
576
+ const pending = this.#pendingInput
577
+ this.#playback.forgetInput(pending)
578
+ this.#inputTranscripts.delete(pending.itemId)
579
+ pending.resetSpeech()
580
+ pending.itemId = undefined
581
+ }
582
+
485
583
  /**
486
584
  * Byte count of the audio buffered for this turn ahead of the speech onset.
487
585
  *
@@ -663,10 +761,10 @@ class RealtimeSession {
663
761
  // Classify before flushing: an out-of-band response runs *alongside* the conversation, so it is
664
762
  // not evidence that a pending turn's transcript has stopped coming.
665
763
 
666
- if (!outOfBand) {
667
- // A new conversational turn starting means a prior turn's input transcription is almost
668
- // certainly not coming anymore, and that any held playback is over (or was cut off without a
669
- // truncation reaching us), so flush both rather than let a turn hang.
764
+ // A new conversational turn starting means a prior turn's input transcription is almost
765
+ // certainly not coming anymore, and that any held playback is over (or was cut off without a
766
+ // truncation reaching us), so flush both rather than let a turn hang.
767
+ if (!outOfBand && !this.#playback) {
670
768
  this.#flushAwaiting(now)
671
769
  this.#flushPlaying(now, true)
672
770
  }
@@ -678,6 +776,7 @@ class RealtimeSession {
678
776
 
679
777
  this.#captureContext(turn)
680
778
  this.#responses.set(String(responseId), turn)
779
+ this.#playback?.start(String(responseId), turn, response)
681
780
  }
682
781
 
683
782
  /**
@@ -713,6 +812,7 @@ class RealtimeSession {
713
812
  }
714
813
 
715
814
  this.#applyCachedTranscript(turn)
815
+ this.#playback?.responseDone(key, response, now)
716
816
 
717
817
  // Hold the turn open for a late input transcription ONLY when transcription is actually enabled
718
818
  // and this item has not already reached a terminal state: otherwise no transcript is ever
@@ -725,6 +825,7 @@ class RealtimeSession {
725
825
  this.#inputTranscriptionEnabled &&
726
826
  !this.#inputTranscripts.has(turn.input.itemId)) {
727
827
  this.#awaiting.push(turn)
828
+ this.#playback?.hold(turn, now, { transcriptPending: true })
728
829
  return
729
830
  }
730
831
 
@@ -796,7 +897,8 @@ class RealtimeSession {
796
897
  // The turn's data is complete, but on a barge-in-capable client the agent's audio may still be
797
898
  // playing and a truncation may yet cut it short — hold the turn rather than submit audio the
798
899
  // listener might never hear.
799
- if (!force && this.#parkForPlayback(turn, now)) return
900
+ if (this.#playback?.hold(turn, now, { force })) return
901
+ if (!this.#playback && !force && this.#parkForPlayback(turn, now)) return
800
902
 
801
903
  // Drop the cached transcript for this turn's input item so the map can't grow across a long
802
904
  // session. Every finalize path goes through here.
@@ -820,24 +922,34 @@ class RealtimeSession {
820
922
  #describeTurn (turn, now) {
821
923
  const { input } = turn
822
924
 
823
- // The VAD speech onset when we have it. The first buffered frame only approximates the onset,
824
- // for a client that appends audio solely while the user talks (client-side turn detection).
825
- const userStart = input.speechStartTime ?? input.audio.startTime
826
925
  const inputFormat = segmentFormat(input.audio, this.#inputAudioMime, this.#inputAudioRate)
827
926
  const outputFormat = segmentFormat(turn.audio, this.#outputAudioMime, this.#outputAudioRate)
828
927
  const inputDurationMs = segmentDurationMs(
829
928
  input.audio.totalDecodedBytes, inputFormat.mimeType, inputFormat.sampleRate
830
929
  )
930
+ // Manual sideband commits have an end boundary but no VAD onset. Complete
931
+ // retrieved audio can anchor their start; a retrieval's arrival time cannot.
932
+ const manualStart = this.#playback && input.speechEndTime !== undefined &&
933
+ input.audio.chunks.length > 0 && inputDurationMs !== undefined && inputDurationMs > 0
934
+ ? input.speechEndTime - inputDurationMs
935
+ : undefined
936
+ // The VAD speech onset when we have it. The first buffered frame only approximates the onset,
937
+ // for a client that appends audio solely while the user talks (client-side turn detection).
938
+ const userStart = this.#playback
939
+ ? input.speechStartTime ?? manualStart
940
+ : input.speechStartTime ?? input.audio.startTime
831
941
  const userEnd = input.speechEndTime ??
832
942
  (userStart === undefined || inputDurationMs === undefined ? undefined : userStart + inputDurationMs)
833
943
 
834
- const agentStart = turn.audio.startTime
944
+ const agentStart = this.#playback ? turn.serverSpeech?.startTime : turn.audio.startTime
835
945
  const playbackMs = segmentDurationMs(
836
946
  turn.audio.totalDecodedBytes, outputFormat.mimeType, outputFormat.sampleRate
837
947
  )
838
- const agentEnd = agentStart === undefined
839
- ? undefined
840
- : (playbackMs === undefined ? (turn.responseDoneTime ?? now) : agentStart + playbackMs)
948
+ const agentEnd = this.#playback
949
+ ? turn.serverSpeech?.finishTime
950
+ : agentStart === undefined
951
+ ? undefined
952
+ : (playbackMs === undefined ? (turn.responseDoneTime ?? now) : agentStart + playbackMs)
841
953
 
842
954
  // The llm span measures model work: it opens at the end of user speech, not when the human
843
955
  // started talking, and closes when generation completes.
@@ -849,11 +961,14 @@ class RealtimeSession {
849
961
  // turn finalized without `response.done` would otherwise finish before its own llm span.
850
962
  const rootFinishTime = Math.max(rootStartTime, llmFinishTime, agentEnd ?? 0, userEnd ?? 0)
851
963
 
964
+ const metadata = { ...this.#sessionConfig }
965
+ if (turn.serverSpeech?.derived) metadata.agent_speech_timing = 'audio_duration'
966
+
852
967
  return {
853
968
  sessionId: this.#sessionId,
854
969
  model: turn.model,
855
970
  basePath: this.#basePath,
856
- metadata: { ...this.#sessionConfig },
971
+ metadata,
857
972
  usage: turn.usage,
858
973
  failed: turn.status === 'failed',
859
974
  error: turn.error,
@@ -944,6 +1059,16 @@ class RealtimeSession {
944
1059
  if (rate) this.#outputAudioRate = rate
945
1060
  }
946
1061
  if (voice != null) this.#sessionConfig.voice = String(voice)
1062
+ const turnDetection = audio?.input?.turn_detection ?? session.turn_detection
1063
+ if (turnDetection !== undefined) {
1064
+ this.#vadSilenceMs = turnDetection?.type === 'server_vad'
1065
+ ? (toFiniteNumber(turnDetection.silence_duration_ms) ?? 0)
1066
+ : 0
1067
+ }
1068
+ this.#playback?.updateFormats(
1069
+ { mimeType: this.#inputAudioMime, sampleRate: this.#inputAudioRate },
1070
+ { mimeType: this.#outputAudioMime, sampleRate: this.#outputAudioRate }
1071
+ )
947
1072
  }
948
1073
 
949
1074
  /**
@@ -80,14 +80,28 @@ class InputTurn {
80
80
  itemId = undefined
81
81
 
82
82
  /**
83
- * Wall clock (epoch ms) when the user actually started speaking, from the VAD speech-onset event.
84
- * This is the start of the user-speech window; the first buffered frame is not, because a
83
+ * Start of the VAD-selected input clip on the wall clock (epoch ms), including prefix padding.
84
+ * This anchors the user-speech window; an arbitrary first buffered frame does not, because a
85
85
  * server-VAD client streams the microphone continuously.
86
86
  *
87
87
  * @type {number | undefined}
88
88
  */
89
89
  speechStartTime = undefined
90
90
 
91
+ /**
92
+ * Start of this VAD clip on the provider's input-buffer clock, including prefix padding.
93
+ * Paired with speech_stopped.audio_end_ms to place retrieved sideband audio.
94
+ *
95
+ * @type {number | undefined}
96
+ */
97
+ speechStartOffsetMs = undefined
98
+
99
+ /** @type {string | undefined} */
100
+ speechItemId = undefined
101
+
102
+ /** @type {number | undefined} */
103
+ speechEndOffsetMs = undefined
104
+
91
105
  /**
92
106
  * Wall clock (epoch ms) when the input audio was committed (roughly the end of user speech). Lets
93
107
  * response latency be measured from real speech-end rather than the padded buffer end.
@@ -111,6 +125,15 @@ class InputTurn {
111
125
  */
112
126
  toolResults = []
113
127
 
128
+ /** Retire a superseded clip without discarding pending text or tool results. */
129
+ resetSpeech () {
130
+ this.discardAudio()
131
+ this.transcript = ''
132
+ this.speechItemId = undefined
133
+ this.speechEndOffsetMs = undefined
134
+ this.speechEndTime = undefined
135
+ }
136
+
114
137
  /**
115
138
  * The input audio buffer was cleared: drop the buffered audio and the speech onset derived from
116
139
  * it, so neither can be attributed to the next response. A commit that already happened is left
@@ -119,6 +142,7 @@ class InputTurn {
119
142
  discardAudio () {
120
143
  this.audio.clear()
121
144
  this.speechStartTime = undefined
145
+ this.speechStartOffsetMs = undefined
122
146
  this.audioBaseMs = undefined
123
147
  }
124
148
  }
@@ -138,6 +162,9 @@ class ResponseTurn {
138
162
  this.audio = new AudioAccumulator(retainAudio)
139
163
  }
140
164
 
165
+ /** @type {{ startTime?: number, finishTime?: number, derived?: boolean } | undefined} */
166
+ serverSpeech = undefined
167
+
141
168
  transcript = new ItemText()
142
169
 
143
170
  text = new ItemText()
@@ -21,16 +21,18 @@ if (isOtelSdkEnabled()) {
21
21
  // @opentelemetry/sdk-trace's TracerProvider instead of sdk-trace-node's
22
22
  // NodeTracerProvider, so the hook above no longer intercepts it. Wrap this
23
23
  // export too, otherwise DD_TRACE_OTEL_ENABLED spans never reach the tracer.
24
- addHook({
25
- name: '@opentelemetry/sdk-trace',
26
- file: 'build/src/TracerProvider.js',
27
- versions: ['*'],
28
- }, (mod) => {
29
- shimmer.wrap(mod, 'TracerProvider', () => {
30
- return tracer.TracerProvider
24
+ for (const file of ['build/src/TracerProvider.js', 'dist/TracerProvider.cjs', 'dist/TracerProvider.mjs']) {
25
+ addHook({
26
+ name: '@opentelemetry/sdk-trace',
27
+ file,
28
+ versions: ['*'],
29
+ }, (mod) => {
30
+ shimmer.wrap(mod, 'TracerProvider', () => {
31
+ return tracer.TracerProvider
32
+ })
33
+ return mod
31
34
  })
32
- return mod
33
- })
35
+ }
34
36
  }
35
37
 
36
38
  function isOtelSdkEnabled () {
@@ -55,20 +55,24 @@ function annotateLayer (layer, matchers) {
55
55
  }
56
56
 
57
57
  /**
58
- * Resolve the route for a dispatched layer. Single-pattern layers carry a
59
- * constant route; only multi-pattern stacks need the per-request `layer.path`
60
- * match the host already computed.
58
+ * Single-pattern layers carry a constant route. Multi-pattern layers use the
59
+ * host's request-local pattern when available, or match its legacy `layer.path`.
61
60
  *
62
61
  * @param {{ captureRoute?: string, needMultiMatch: boolean,
63
62
  * matchers: Array<{ path?: string, regex?: RegExp }> }} meta
64
63
  * @param {{ path?: string }} layer
64
+ * @param {import('node:http').IncomingMessage} [req]
65
+ * @param {symbol} [matchedRoute]
65
66
  * @returns {string | undefined}
66
67
  */
67
- function resolveLayerRoute (meta, layer) {
68
+ function resolveLayerRoute (meta, layer, req, matchedRoute) {
68
69
  if (!meta.needMultiMatch) return meta.captureRoute
69
70
 
71
+ const pattern = matchedRoute && req[matchedRoute]
72
+ if (typeof pattern === 'string') return pattern
73
+
70
74
  for (const matcher of meta.matchers) {
71
- if (matcher.regex?.test(layer.path)) return matcher.path
75
+ if (matchedRoute ? matcher.regex === pattern : matcher.regex?.test(layer.path)) return matcher.path
72
76
  }
73
77
  }
74
78
 
@@ -80,11 +84,13 @@ function resolveLayerRoute (meta, layer) {
80
84
  * matchers: Array<{ path?: string, regex?: RegExp }> }} meta
81
85
  * @param {{ path?: string }} layer
82
86
  * @param {Function} next
87
+ * @param {import('node:http').IncomingMessage} req
88
+ * @param {symbol | undefined} matchedRoute
83
89
  * @returns {string | undefined | typeof ROUTE_RESOLUTION_FAILED}
84
90
  */
85
- function resolveLayerRouteOrForwardError (meta, layer, next) {
91
+ function resolveLayerRouteOrForwardError (meta, layer, next, req, matchedRoute) {
86
92
  try {
87
- return resolveLayerRoute(meta, layer)
93
+ return resolveLayerRoute(meta, layer, req, matchedRoute)
88
94
  } catch (error) {
89
95
  next(error)
90
96
  return ROUTE_RESOLUTION_FAILED
@@ -121,13 +127,14 @@ function adoptRequestNext (req, hostNext, wrappedNext) {
121
127
  * span is published only for the layer the host actually runs.
122
128
  *
123
129
  * @param {string} name Channel namespace (`apm:<name>:middleware:*`).
130
+ * @param {symbol} [matchedRoute] Native request-local route key, when provided by the host.
124
131
  * @returns {{
125
132
  * wrapLayerRequest: (originalRequest: Function) => Function,
126
133
  * wrapLayerError: (originalError: Function) => Function,
127
134
  * wrapLegacyHandle: (layer: object, original: Function, guardRepeatedNext?: boolean) => Function
128
135
  * }}
129
136
  */
130
- function createLayerDispatchWrappers (name) {
137
+ function createLayerDispatchWrappers (name, matchedRoute) {
131
138
  const enterChannel = channel(`apm:${name}:middleware:enter`)
132
139
  const exitChannel = channel(`apm:${name}:middleware:exit`)
133
140
  const finishChannel = channel(`apm:${name}:middleware:finish`)
@@ -188,7 +195,7 @@ function createLayerDispatchWrappers (name) {
188
195
 
189
196
  let route = meta.captureRoute
190
197
  if (meta.needMultiMatch) {
191
- route = resolveLayerRouteOrForwardError(meta, this, next)
198
+ route = resolveLayerRouteOrForwardError(meta, this, next, req, matchedRoute)
192
199
  if (route === ROUTE_RESOLUTION_FAILED) return
193
200
  }
194
201
 
@@ -217,7 +224,7 @@ function createLayerDispatchWrappers (name) {
217
224
 
218
225
  let route = meta.captureRoute
219
226
  if (meta.needMultiMatch) {
220
- route = resolveLayerRouteOrForwardError(meta, this, next)
227
+ route = resolveLayerRouteOrForwardError(meta, this, next, req, matchedRoute)
221
228
  if (route === ROUTE_RESOLUTION_FAILED) return
222
229
  }
223
230
 
@@ -644,10 +651,26 @@ function wrapHandleRequest (original) {
644
651
  }
645
652
  }
646
653
 
654
+ /** @type {Map<string | undefined, symbol>} */
655
+ const matchedRouteSymbols = new Map()
656
+
657
+ addHook({ name: 'router', file: 'lib/symbols.js', versions: ['>=2'] },
658
+ /**
659
+ * @param {{ matchedRoute: symbol }} symbols
660
+ * @param {string} version
661
+ * @param {boolean} isIitm
662
+ * @param {{ moduleBaseDir?: string }} hookMeta
663
+ */
664
+ function captureMatchedRoute (symbols, version, isIitm, { moduleBaseDir }) {
665
+ matchedRouteSymbols.set(moduleBaseDir, symbols.matchedRoute)
666
+ return symbols
667
+ })
668
+
647
669
  addHook({
648
670
  name: 'router', file: 'lib/layer.js', versions: ['>=2'],
649
- }, Layer => {
650
- const { wrapLayerRequest, wrapLayerError } = createLayerDispatchWrappers('router')
671
+ }, (Layer, version, isIitm, { moduleBaseDir }) => {
672
+ const matchedRoute = matchedRouteSymbols.get(moduleBaseDir)
673
+ const { wrapLayerRequest, wrapLayerError } = createLayerDispatchWrappers('router', matchedRoute)
651
674
 
652
675
  // `handleRequest` carries two concerns: the middleware dispatch span and the
653
676
  // param-start publish (`wrapHandleRequest`). Wrap the dispatch first so it
@@ -1197,6 +1197,11 @@ function safeWorkspaceProject (ctx) {
1197
1197
  return project
1198
1198
  }
1199
1199
 
1200
+ function hasCachedSpecifications (ctx) {
1201
+ const cachedSpecs = ctx?.specifications?._cachedSpecs
1202
+ return typeof cachedSpecs?.size === 'number' && cachedSpecs.size > 0
1203
+ }
1204
+
1200
1205
  function getSortWrapper (sort, frameworkVersion) {
1201
1206
  return async function () {
1202
1207
  if (this.ctx.config.shard && this.ctx.state.pathsSet.size > 0 && arguments[0].length === 0) {
@@ -1229,13 +1234,16 @@ function getFinishWrapper (exitOrClose) {
1229
1234
 
1230
1235
  // pathsSet contains candidates before sharding, including files that never run.
1231
1236
  const hasNoTestFiles = this.state.pathsSet.size === 0
1232
- const isEmptyShard = emptyShardContexts.has(this)
1237
+ const files = this.state.getFiles()
1238
+ const tests = getTypeTasks(files)
1239
+ const isEmptyShard = emptyShardContexts.has(this) ||
1240
+ (this.config.shard && this.config.passWithNoTests && !areAllSuitesSkipped &&
1241
+ files.length === 0 && hasCachedSpecifications(this))
1233
1242
  const hasUnexpectedEmptySession = hasNoTestFiles && !isEmptyShard &&
1234
1243
  !areAllSuitesSkipped && !this.config.passWithNoTests
1235
1244
  if (!error && hasUnexpectedEmptySession) {
1236
1245
  error = new Error('No test files were found.')
1237
1246
  }
1238
- const tests = getTypeTasks(this.state.getFiles())
1239
1247
  const hasExecutedTests = tests.some(test =>
1240
1248
  test.mode !== 'skip' && test.mode !== 'todo' &&
1241
1249
  (test.result?.state === 'pass' || test.result?.state === 'fail')
@@ -23,7 +23,7 @@ const {
23
23
  TEST_SUITE_EXECUTION_ID,
24
24
  } = require('../../dd-trace/src/plugins/util/test')
25
25
  const { publishWithCompletion } = require('./helpers/channel')
26
- const { addHook, channel, tracingChannel } = require('./helpers/instrument')
26
+ const { channel, tracingChannel } = require('./helpers/instrument')
27
27
  const {
28
28
  CONFIGURATION_REQUEST,
29
29
  CONFIGURATION_RESPONSE,
@@ -97,7 +97,8 @@ if (loadCh.hasSubscribers) {
97
97
 
98
98
  const coordinatorStates = new WeakMap()
99
99
  const emptyShardConfigurations = new WeakSet()
100
- const localRunnerVersions = new WeakMap()
100
+ // A WebdriverIO process runs a single @wdio/local-runner version.
101
+ let localRunnerVersion
101
102
  const rumBrowsers = new Set()
102
103
  const rumCorrelationBrowsers = new Set()
103
104
  const rumRunnerBrowsers = new WeakSet()
@@ -115,15 +116,14 @@ function getCurrentRumContext () {
115
116
  return globalThis.window
116
117
  }
117
118
 
118
- addHook({
119
- name: '@wdio/local-runner',
120
- versions: ['>=9.0.0'],
121
- file: 'build/index.js',
122
- patchDefault: true,
123
- }, (LocalRunner, version) => {
124
- localRunnerVersions.set(LocalRunner, version)
125
- return LocalRunner
126
- })
119
+ /**
120
+ * @param {import('./helpers/rewriter/instrumentation-registry').Activation} activation
121
+ */
122
+ function recordLocalRunnerVersion ({ moduleName, version }) {
123
+ if (moduleName === '@wdio/local-runner') localRunnerVersion = version
124
+ }
125
+
126
+ exports.recordLocalRunnerVersion = recordLocalRunnerVersion
127
127
 
128
128
  /**
129
129
  * Returns whether this browser can preload and clean correlation across every browsing context.
@@ -1165,7 +1165,7 @@ function getCoordinatorState (localRunner) {
1165
1165
  initializationCallbacks: [],
1166
1166
  sessionStarted: false,
1167
1167
  finished: false,
1168
- frameworkVersion: localRunnerVersions.get(localRunner.constructor),
1168
+ frameworkVersion: localRunnerVersion,
1169
1169
  testFrameworkAdapter: getRunnerConfiguration(localRunner)?.framework,
1170
1170
  activeWorkers: 0,
1171
1171
  attemptToFixExecutions: new Map(),
@@ -0,0 +1,50 @@
1
+ 'use strict'
2
+
3
+ const TracingPlugin = require('../../dd-trace/src/plugins/tracing')
4
+
5
+ class AsyncMutexPlugin extends TracingPlugin {
6
+ static id = 'async-mutex'
7
+ static prefix = 'tracing:orchestrion:async-mutex:Semaphore_acquire'
8
+
9
+ bindStart (ctx) {
10
+ const weight = ctx.arguments?.[0] ?? 1
11
+ const priority = ctx.arguments?.[1] ?? 0
12
+ const semaphore = ctx.self
13
+
14
+ const metrics = {}
15
+ if (weight !== 1) metrics['async_mutex.weight'] = weight
16
+ if (priority !== 0) metrics['async_mutex.priority'] = priority
17
+ // `_couldLockImmediately` is the library's own predicate for "would this queue". Guarded so a
18
+ // version that drops it reports nothing rather than a wrong answer.
19
+ if (typeof semaphore?._couldLockImmediately === 'function') {
20
+ metrics['async_mutex.contended'] = semaphore._couldLockImmediately(weight, priority) ? 0 : 1
21
+ }
22
+
23
+ this.startSpan('async-mutex.acquire', {
24
+ service: this.config.service || this._tracerConfig.service,
25
+ resource: 'acquire',
26
+ meta: {
27
+ component: 'async-mutex',
28
+ },
29
+ metrics,
30
+ }, ctx)
31
+
32
+ return ctx.currentStore
33
+ }
34
+
35
+ end (ctx) {
36
+ if (ctx.error === undefined) return
37
+
38
+ this.finish(ctx)
39
+
40
+ return ctx.parentStore
41
+ }
42
+
43
+ asyncEnd (ctx) {
44
+ this.finish(ctx)
45
+
46
+ return ctx.parentStore
47
+ }
48
+ }
49
+
50
+ module.exports = AsyncMutexPlugin