dd-trace 6.25.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 (141) hide show
  1. package/README.md +3 -0
  2. package/ci/cypress/support.js +2 -1
  3. package/ci/vitest-no-worker-init-node-setup.mjs +2 -1
  4. package/ci/vitest-no-worker-init-runner-setup.mjs +2 -1
  5. package/ci/vitest-no-worker-init-setup.mjs +729 -724
  6. package/ci/vitest-no-worker-init-v5-setup.mjs +2 -1
  7. package/package.json +33 -30
  8. package/packages/datadog-esbuild/index.js +8 -15
  9. package/packages/datadog-esbuild/src/log.js +2 -29
  10. package/packages/datadog-instrumentations/src/ai.js +6 -1
  11. package/packages/datadog-instrumentations/src/cypress-config.js +20 -9
  12. package/packages/datadog-instrumentations/src/helpers/bundler-esm-exports.js +23 -1
  13. package/packages/datadog-instrumentations/src/helpers/bundler-log.js +38 -0
  14. package/packages/datadog-instrumentations/src/helpers/bundler-transform.js +9 -6
  15. package/packages/datadog-instrumentations/src/helpers/fetch.js +51 -6
  16. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +6 -0
  17. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +8 -0
  18. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-client.js +30 -0
  19. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-server.js +23 -0
  20. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/next.js +21 -0
  21. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/postgres.js +33 -4
  22. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +30 -0
  23. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +6 -0
  24. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms/postgres.js +122 -0
  25. package/packages/datadog-instrumentations/src/microgateway-core.js +1 -2
  26. package/packages/datadog-instrumentations/src/modelcontextprotocol-client.js +21 -0
  27. package/packages/datadog-instrumentations/src/modelcontextprotocol-sdk.js +7 -1
  28. package/packages/datadog-instrumentations/src/modelcontextprotocol-server.js +41 -0
  29. package/packages/datadog-instrumentations/src/next.js +184 -20
  30. package/packages/datadog-instrumentations/src/router.js +35 -12
  31. package/packages/datadog-instrumentations/src/vitest-main.js +10 -2
  32. package/packages/datadog-plugin-aws-lambda/src/arn.js +41 -0
  33. package/packages/datadog-plugin-aws-lambda/src/event-type-guards.js +170 -0
  34. package/packages/datadog-plugin-aws-lambda/src/trigger.js +339 -0
  35. package/packages/datadog-plugin-aws-sdk/src/services/dynamodb.js +7 -0
  36. package/packages/datadog-plugin-aws-sdk/src/services/kinesis.js +32 -10
  37. package/packages/datadog-plugin-aws-sdk/src/services/lambda.js +10 -1
  38. package/packages/datadog-plugin-aws-sdk/src/services/sqs.js +4 -0
  39. package/packages/datadog-plugin-aws-sdk/src/services/stepfunctions.js +3 -0
  40. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +30 -4
  41. package/packages/datadog-plugin-cypress/src/support.mjs +1353 -0
  42. package/packages/datadog-plugin-express/src/code_origin.js +2 -2
  43. package/packages/datadog-plugin-fastify/src/code_origin.js +2 -2
  44. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +10 -0
  45. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +2 -0
  46. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +7 -0
  47. package/packages/datadog-plugin-google-cloud-pubsub/src/resource-names.js +24 -0
  48. package/packages/datadog-plugin-graphql/src/tools/transforms.js +1 -0
  49. package/packages/datadog-plugin-http/src/client.js +2 -1
  50. package/packages/datadog-plugin-http2/src/client.js +2 -1
  51. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/tracing.js +28 -2
  52. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/utils.js +1 -0
  53. package/packages/datadog-plugin-mongodb-core/src/query.js +17 -1
  54. package/packages/datadog-plugin-postgres/src/index.js +118 -41
  55. package/packages/datadog-plugin-supabase/src/supabase-auth-js-gotrueclient-getuser.js +18 -8
  56. package/packages/datadog-plugin-supabase/src/supabase-functions-js-functionsclient-invoke.js +49 -13
  57. package/packages/datadog-plugin-supabase/src/supabase-storage-js-handle-request.js +34 -9
  58. package/packages/datadog-plugin-vitest/src/index.js +3 -2
  59. package/packages/datadog-plugin-ws/src/close.js +3 -5
  60. package/packages/datadog-plugin-ws/src/producer.js +1 -4
  61. package/packages/datadog-plugin-ws/src/receiver.js +3 -5
  62. package/packages/datadog-plugin-ws/src/server.js +44 -13
  63. package/packages/datadog-vite/index.js +537 -0
  64. package/packages/datadog-vite/src/log.js +5 -0
  65. package/packages/datadog-webpack/src/log.js +2 -29
  66. package/packages/dd-trace/src/aiguard/index.js +1 -1
  67. package/packages/dd-trace/src/aiguard/integrations/index.js +6 -5
  68. package/packages/dd-trace/src/appsec/blocking/index.js +17 -1
  69. package/packages/dd-trace/src/appsec/channels.js +7 -0
  70. package/packages/dd-trace/src/appsec/downstream_requests.js +105 -0
  71. package/packages/dd-trace/src/appsec/graphql.js +10 -13
  72. package/packages/dd-trace/src/appsec/handlers/auth.js +1 -3
  73. package/packages/dd-trace/src/appsec/handlers/http-request.js +60 -65
  74. package/packages/dd-trace/src/appsec/handlers/http-response.js +61 -7
  75. package/packages/dd-trace/src/appsec/handlers/payments.js +23 -27
  76. package/packages/dd-trace/src/appsec/index.js +6 -0
  77. package/packages/dd-trace/src/appsec/lambda.js +17 -17
  78. package/packages/dd-trace/src/appsec/rasp/command_injection.js +4 -4
  79. package/packages/dd-trace/src/appsec/rasp/index.js +8 -1
  80. package/packages/dd-trace/src/appsec/rasp/lfi.js +2 -2
  81. package/packages/dd-trace/src/appsec/rasp/sql_injection.js +7 -17
  82. package/packages/dd-trace/src/appsec/rasp/ssrf.js +80 -16
  83. package/packages/dd-trace/src/appsec/rasp/utils.js +33 -3
  84. package/packages/dd-trace/src/appsec/recommended.json +70 -3
  85. package/packages/dd-trace/src/appsec/reporter.js +9 -0
  86. package/packages/dd-trace/src/appsec/sdk/set_user.js +3 -3
  87. package/packages/dd-trace/src/appsec/sdk/track_event.js +4 -4
  88. package/packages/dd-trace/src/appsec/sdk/user_blocking.js +1 -1
  89. package/packages/dd-trace/src/appsec/user_tracking.js +6 -8
  90. package/packages/dd-trace/src/appsec/waf/index.js +65 -6
  91. package/packages/dd-trace/src/appsec/waf/waf_context_wrapper.js +33 -38
  92. package/packages/dd-trace/src/appsec/waf/waf_manager.js +18 -2
  93. package/packages/dd-trace/src/config/generated-config-types.d.ts +4 -2
  94. package/packages/dd-trace/src/config/index.js +46 -26
  95. package/packages/dd-trace/src/config/parsers.js +35 -0
  96. package/packages/dd-trace/src/config/remote-config-layers.js +38 -0
  97. package/packages/dd-trace/src/config/remote_config.js +2 -1
  98. package/packages/dd-trace/src/config/supported-configurations.json +14 -6
  99. package/packages/dd-trace/src/datastreams/fnv.js +27 -0
  100. package/packages/dd-trace/src/datastreams/pathway.js +113 -28
  101. package/packages/dd-trace/src/datastreams/processor.js +5 -4
  102. package/packages/dd-trace/src/debugger/config.js +1 -1
  103. package/packages/dd-trace/src/debugger/devtools_client/request-options.js +7 -9
  104. package/packages/dd-trace/src/debugger/devtools_client/send.js +1 -1
  105. package/packages/dd-trace/src/debugger/devtools_client/state.js +3 -1
  106. package/packages/dd-trace/src/debugger/devtools_client/tags.js +1 -1
  107. package/packages/dd-trace/src/debugger/index.js +2 -2
  108. package/packages/dd-trace/src/debugger/inspect-segment.js +3 -2
  109. package/packages/dd-trace/src/debugger/pause-duration-histogram.js +4 -1
  110. package/packages/dd-trace/src/debugger/probe_sampler.js +39 -17
  111. package/packages/dd-trace/src/debugger/unsupported-runtime.js +2 -0
  112. package/packages/dd-trace/src/git_metadata.js +2 -1
  113. package/packages/dd-trace/src/index.js +6 -3
  114. package/packages/dd-trace/src/lambda/facade.js +6 -5
  115. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/index.js +54 -3
  116. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/utils.js +81 -1
  117. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +3 -0
  118. package/packages/dd-trace/src/openfeature/configuration_source.js +20 -0
  119. package/packages/dd-trace/src/plugins/ci_plugin.js +104 -9
  120. package/packages/dd-trace/src/plugins/index.js +2 -0
  121. package/packages/dd-trace/src/plugins/util/ci.js +34 -0
  122. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +9 -14
  123. package/packages/dd-trace/src/plugins/util/test.js +28 -1
  124. package/packages/dd-trace/src/plugins/util/url.js +8 -5
  125. package/packages/dd-trace/src/plugins/util/user-provided-git.js +4 -4
  126. package/packages/dd-trace/src/process-tags/index.js +1 -1
  127. package/packages/dd-trace/src/profiler.js +74 -12
  128. package/packages/dd-trace/src/profiling/profiler.js +30 -2
  129. package/packages/dd-trace/src/profiling/profilers/space.js +3 -1
  130. package/packages/dd-trace/src/profiling/profilers/wall.js +4 -4
  131. package/packages/dd-trace/src/profiling/remote-config.js +354 -0
  132. package/packages/dd-trace/src/profiling/runtime-capabilities.js +11 -0
  133. package/packages/dd-trace/src/propagation-hash/index.js +7 -0
  134. package/packages/dd-trace/src/proxy.js +13 -1
  135. package/vendor/dist/@opentelemetry/core/LICENSE +11 -0
  136. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  137. package/vite.d.ts +7 -0
  138. package/vite.js +3 -0
  139. package/lambda.d.ts +0 -39
  140. package/lambda.js +0 -3
  141. package/packages/datadog-plugin-cypress/src/support.js +0 -1348
@@ -1,831 +1,794 @@
1
1
  const { afterEach, beforeAll, beforeEach, inject } =
2
2
  globalThis[Symbol.for('dd-trace.vitest.api')] || await import('vitest')
3
3
 
4
- // Instrumentation-less setup for DD_EXPERIMENTAL_TEST_OPT_VITEST_NO_WORKER_INIT.
5
- // It applies Test Optimization execution changes without initializing dd-trace and also supports Browser Mode.
6
- const VITEST_NO_WORKER_INIT_ACTIVE_ENV = 'DD_TEST_OPT_VITEST_NO_WORKER_INIT_ACTIVE'
7
- const SERIALIZED_CONTEXT_PREFIX = '\0dd-vitest-context:'
8
- const providedContext = getProvidedContext()
9
- const isNoWorkerInitActive = providedContext.isActive ?? getIsNoWorkerInitActive()
10
- const attemptToFixTests = providedContext.attemptToFixTests || {}
11
- const attemptToFixRetries = providedContext.attemptToFixRetries || 0
12
- const disabledTests = providedContext.disabledTests || {}
13
- const efdSuiteAdmissionBrowserCommand = providedContext.efdSuiteAdmissionBrowserCommand
14
- const earlyFlakeDetectionRetryPolicy = providedContext.earlyFlakeDetectionRetryPolicy || {
15
- durationRetryCounts: [],
16
- schedulingRetryCount: 0,
17
- }
18
- const earlyFlakeDetectionRetries = earlyFlakeDetectionRetryPolicy.schedulingRetryCount
19
- const dynamicAtrRetryPolicy = providedContext.dynamicAtrRetryPolicy
20
- const flakyTestRetriesConfiguration = providedContext.flakyTestRetriesConfiguration
21
- const isEfdSuiteAdmissionEnabled = providedContext.isEfdSuiteAdmissionEnabled === true
22
- const isEarlyFlakeDetectionEnabled = providedContext.isEarlyFlakeDetectionEnabled === true
23
- const knownTests = providedContext.knownTests || {}
24
- const modifiedFiles = providedContext.modifiedFiles || {}
25
- const quarantinedTests = providedContext.quarantinedTests || {}
26
- const isRumCorrelationEnabled = providedContext.isRumCorrelationEnabled !== false
27
- const rumTestExecutionIdCookieName = providedContext.rumTestExecutionIdCookieName
28
- const testPropertiesByFilepath = providedContext.testPropertiesByFilepath || {}
29
- const setVitestTaskFn = globalThis[Symbol.for('dd-trace.vitest.set-fn')]
30
- const skipVitestTask = globalThis[Symbol.for('dd-trace.vitest.skip-task')]
31
- const importVitestBrowserContext = globalThis[Symbol.for('dd-trace.vitest.browser-context-importer')]
32
- const earlyFlakeDetectionRetriesByTask = new WeakMap()
33
- const earlyFlakeDetectionSkippedResults = new WeakMap()
34
- const earlyFlakeDetectionStartByTask = new WeakMap()
35
- const nextAttemptIndexByTask = new WeakMap()
36
- const retryAttemptIndexByTask = new WeakMap()
37
- const dynamicAtrExecutionStartByTask = new WeakMap()
38
- const usedRumTestExecutionIds = new Set()
39
- let browserCommands
40
- let now
41
- let timeOrigin
42
- // Use an unfaked monotonic clock in Node and Vitest's parent frame in Browser Mode.
43
- if (typeof globalThis.process?.uptime === 'function') {
44
- now = () => globalThis.process.uptime() * 1000
45
- timeOrigin = Date.now() - now()
46
- } else {
47
- const clock = globalThis.window?.parent && globalThis.window.parent !== globalThis.window
48
- ? globalThis.window.parent.performance
49
- : globalThis.performance
50
- now = clock ? clock.now.bind(clock) : Date.now
51
- timeOrigin = Number.isFinite(clock?.timeOrigin) ? clock.timeOrigin : Date.now() - now()
52
- }
53
-
54
4
  /**
55
- * Requests permission from the Vitest main process to schedule Browser Mode EFD retries for one suite.
56
- *
57
- * @param {string} testSuite
58
- * @param {boolean} hasNewTest
59
- * @returns {Promise<boolean>}
5
+ * Registers execution hooks with fresh state for each spec, while keeping the implementation module cached.
60
6
  */
61
- async function requestBrowserEfdSuiteAdmission (testSuite, hasNewTest) {
62
- try {
63
- if (!browserCommands) {
64
- const vitestBrowser = await importVitestBrowserContext()
65
- browserCommands = vitestBrowser.commands
66
- }
67
- return await browserCommands[efdSuiteAdmissionBrowserCommand](testSuite, hasNewTest) === true
68
- } catch (error) {
69
- // Browser Mode setup runs without dd-trace, so the tracer logger is unavailable.
70
- globalThis.console?.error('Datadog Test Optimization could not request Vitest EFD suite admission.', error)
71
- return false
72
- }
73
- }
74
-
75
- if (isNoWorkerInitActive) {
76
- // eslint-disable-next-line no-empty-pattern
77
- beforeAll(async function ({}, suite) {
78
- suite ||= arguments[0]
79
- const efdSuiteCandidate = getEarlyFlakeDetectionSuiteCandidate(suite)
80
- const isEfdSuiteAdmissionAllowed = !efdSuiteCandidate || !isEfdSuiteAdmissionEnabled ||
81
- await requestBrowserEfdSuiteAdmission(efdSuiteCandidate.testSuite, efdSuiteCandidate.hasNewTest)
82
- applyExecutionChanges(suite, isEfdSuiteAdmissionAllowed)
83
- })
84
-
85
- beforeEach(function ({ onTestFinished, task, skip }) {
86
- const testSuite = getTestSuite(task)
87
- const testName = getTestName(task)
88
- const annotations = task.meta?.__ddTestOptAnnotations || {}
89
- const isAttemptToFixTest = attemptToFixTests[testSuite]?.[testName] && !annotations.noAutoRetry
90
- const isEarlyFlakeDetectionTestAttempt = isEarlyFlakeDetectionTask(task)
91
- const isQuarantinedTest = quarantinedTests[testSuite]?.[testName] &&
92
- !annotations.mustFail && !isAttemptToFixTest
93
- const attemptIndex = getNextAttemptIndex(task)
94
- const attemptStart = now()
95
- if (task.retry?.__ddTestOptAtr && retryAttemptIndexByTask.get(task).index === 0) {
96
- const executionStart = task.result.repeatCount > 0 ? attemptStart : task.result.startTime - timeOrigin
97
- dynamicAtrExecutionStartByTask.set(task, executionStart)
98
- task.meta.__ddTestOptAtrRetries = undefined
99
- }
100
- if (attemptIndex > 0) {
101
- recordTestOptimizationStatus(task, attemptIndex - 1)
102
- }
103
-
104
- if (!isAttemptToFixTest && !annotations.mustFail && disabledTests[testSuite]?.[testName]) {
105
- skip('Skipped by Datadog Test Optimization')
106
- } else if (isAttemptToFixTest && attemptIndex > 0) {
107
- task.result.state = 'run'
108
- } else if (isEarlyFlakeDetectionTestAttempt) {
109
- const isSkippedRepeat = prepareEarlyFlakeDetectionAttempt(task, attemptIndex, skip)
110
- if (!isSkippedRepeat && attemptIndex > 0) {
111
- task.result.state = 'run'
7
+ export function setup () {
8
+ // Instrumentation-less setup for DD_EXPERIMENTAL_TEST_OPT_VITEST_NO_WORKER_INIT.
9
+ // It applies Test Optimization execution changes without initializing dd-trace and also supports Browser Mode.
10
+ const VITEST_NO_WORKER_INIT_ACTIVE_ENV = 'DD_TEST_OPT_VITEST_NO_WORKER_INIT_ACTIVE'
11
+ const SERIALIZED_CONTEXT_PREFIX = '\0dd-vitest-context:'
12
+ const providedContext = getProvidedContext()
13
+ const isNoWorkerInitActive = providedContext.isActive ?? getIsNoWorkerInitActive()
14
+ const attemptToFixTests = providedContext.attemptToFixTests || {}
15
+ const attemptToFixRetries = providedContext.attemptToFixRetries || 0
16
+ const disabledTests = providedContext.disabledTests || {}
17
+ const efdSuiteAdmissionBrowserCommand = providedContext.efdSuiteAdmissionBrowserCommand
18
+ const earlyFlakeDetectionRetryPolicy = providedContext.earlyFlakeDetectionRetryPolicy || {
19
+ durationRetryCounts: [],
20
+ schedulingRetryCount: 0,
21
+ }
22
+ const earlyFlakeDetectionRetries = earlyFlakeDetectionRetryPolicy.schedulingRetryCount
23
+ const dynamicAtrRetryPolicy = providedContext.dynamicAtrRetryPolicy
24
+ const flakyTestRetriesConfiguration = providedContext.flakyTestRetriesConfiguration
25
+ const isEfdSuiteAdmissionEnabled = providedContext.isEfdSuiteAdmissionEnabled === true
26
+ const isEarlyFlakeDetectionEnabled = providedContext.isEarlyFlakeDetectionEnabled === true
27
+ const knownTests = providedContext.knownTests || {}
28
+ const modifiedFiles = providedContext.modifiedFiles || {}
29
+ const quarantinedTests = providedContext.quarantinedTests || {}
30
+ const isRumCorrelationEnabled = providedContext.isRumCorrelationEnabled !== false
31
+ const rumTestExecutionIdCookieName = providedContext.rumTestExecutionIdCookieName
32
+ const testPropertiesByFilepath = providedContext.testPropertiesByFilepath || {}
33
+ const setVitestTaskFn = globalThis[Symbol.for('dd-trace.vitest.set-fn')]
34
+ const skipVitestTask = globalThis[Symbol.for('dd-trace.vitest.skip-task')]
35
+ const importVitestBrowserContext = globalThis[Symbol.for('dd-trace.vitest.browser-context-importer')]
36
+ const earlyFlakeDetectionRetriesByTask = new WeakMap()
37
+ const earlyFlakeDetectionSkippedResults = new WeakMap()
38
+ const earlyFlakeDetectionStartByTask = new WeakMap()
39
+ const nextAttemptIndexByTask = new WeakMap()
40
+ const retryAttemptIndexByTask = new WeakMap()
41
+ const dynamicAtrExecutionStartByTask = new WeakMap()
42
+ const usedRumTestExecutionIds = new Set()
43
+ let browserCommands
44
+ let now
45
+ let timeOrigin
46
+ // Use an unfaked monotonic clock in Node and Vitest's parent frame in Browser Mode.
47
+ if (typeof globalThis.process?.uptime === 'function') {
48
+ now = () => globalThis.process.uptime() * 1000
49
+ timeOrigin = Date.now() - now()
50
+ } else {
51
+ const clock = globalThis.window?.parent && globalThis.window.parent !== globalThis.window
52
+ ? globalThis.window.parent.performance
53
+ : globalThis.performance
54
+ now = clock ? clock.now.bind(clock) : Date.now
55
+ timeOrigin = Number.isFinite(clock?.timeOrigin) ? clock.timeOrigin : Date.now() - now()
56
+ }
57
+
58
+ /**
59
+ * Requests permission from the Vitest main process to schedule Browser Mode EFD retries for one suite.
60
+ *
61
+ * @param {string} testSuite
62
+ * @param {boolean} hasNewTest
63
+ * @returns {Promise<boolean>}
64
+ */
65
+ async function requestBrowserEfdSuiteAdmission (testSuite, hasNewTest) {
66
+ try {
67
+ if (!browserCommands) {
68
+ const vitestBrowser = await importVitestBrowserContext()
69
+ browserCommands = vitestBrowser.commands
112
70
  }
71
+ return await browserCommands[efdSuiteAdmissionBrowserCommand](testSuite, hasNewTest) === true
72
+ } catch (error) {
73
+ // Browser Mode setup runs without dd-trace, so the tracer logger is unavailable.
74
+ globalThis.console?.error('Datadog Test Optimization could not request Vitest EFD suite admission.', error)
75
+ return false
113
76
  }
77
+ }
114
78
 
115
- prepareRumCorrelation(task, attemptIndex)
116
-
117
- onTestFinished(() => {
118
- recordTestAttemptTiming(task, attemptIndex, attemptStart)
119
- recordRetryErrorCount(task)
120
- if (isEarlyFlakeDetectionTestAttempt || isQuarantinedTest ||
121
- (isAttemptToFixTest && attemptIndex === getFinalAttemptIndex(task))) {
122
- if (isAttemptToFixTest || isEarlyFlakeDetectionTestAttempt) {
123
- recordTestOptimizationStatus(task, attemptIndex, attemptIndex === getFinalAttemptIndex(task))
124
- }
125
- switchQuarantinedFinalFailure(task)
126
- }
127
- finishRumCorrelation(task, attemptIndex)
79
+ if (isNoWorkerInitActive) {
80
+ // eslint-disable-next-line no-empty-pattern
81
+ beforeAll(async function ({}, suite) {
82
+ suite ||= arguments[0]
83
+ const efdSuiteCandidate = getEarlyFlakeDetectionSuiteCandidate(suite)
84
+ const isEfdSuiteAdmissionAllowed = !efdSuiteCandidate || !isEfdSuiteAdmissionEnabled ||
85
+ await requestBrowserEfdSuiteAdmission(efdSuiteCandidate.testSuite, efdSuiteCandidate.hasNewTest)
86
+ applyExecutionChanges(suite, isEfdSuiteAdmissionAllowed)
128
87
  })
129
- })
130
-
131
- afterEach(function ({ task }) {
132
- const attemptIndex = task.meta.__ddTestOptCurrentAttemptIndex
133
- const restoredEarlyFlakeDetectionResult = restoreEarlyFlakeDetectionSkippedResult(task)
134
- if (!restoredEarlyFlakeDetectionResult && attemptIndex === getFinalAttemptIndex(task)) {
135
- recordTestOptimizationStatus(task, attemptIndex)
136
- }
137
- if (!restoredEarlyFlakeDetectionResult) {
138
- switchQuarantinedFinalFailure(task)
139
- }
140
- })
141
- }
142
-
143
- function applyExecutionChanges (suite, isEfdSuiteAdmissionAllowed) {
144
- const tasks = suite?.tasks
145
- if (tasks) {
146
- for (const task of tasks) {
147
- if (task.type === 'suite') {
148
- applyExecutionChanges(task, isEfdSuiteAdmissionAllowed)
149
- continue
150
- }
151
88
 
89
+ beforeEach(function ({ onTestFinished, task, skip }) {
152
90
  const testSuite = getTestSuite(task)
153
91
  const testName = getTestName(task)
154
92
  const annotations = task.meta?.__ddTestOptAnnotations || {}
155
- if (annotations.noAutoRetry && !annotations.hasFrameworkRetry &&
156
- (task.retry?.__ddTestOptAtr || isAutomaticRetryProject(task))) {
157
- task.retry = 0
93
+ const isAttemptToFixTest = attemptToFixTests[testSuite]?.[testName] && !annotations.noAutoRetry
94
+ const isEarlyFlakeDetectionTestAttempt = isEarlyFlakeDetectionTask(task)
95
+ const isQuarantinedTest = quarantinedTests[testSuite]?.[testName] &&
96
+ !annotations.mustFail && !isAttemptToFixTest
97
+ const attemptIndex = getNextAttemptIndex(task)
98
+ const attemptStart = now()
99
+ if (task.retry?.__ddTestOptAtr && retryAttemptIndexByTask.get(task).index === 0) {
100
+ const executionStart = task.result.repeatCount > 0 ? attemptStart : task.result.startTime - timeOrigin
101
+ dynamicAtrExecutionStartByTask.set(task, executionStart)
102
+ task.meta.__ddTestOptAtrRetries = undefined
158
103
  }
159
- if (attemptToFixTests[testSuite]?.[testName] && !annotations.noAutoRetry) {
160
- task.retry = 0
161
- task.repeats = attemptToFixRetries
162
- task.meta.__ddTestOptAtfRetries = attemptToFixRetries
163
- } else if (disabledTests[testSuite]?.[testName] && !annotations.mustFail) {
164
- task.mode = 'skip'
165
- } else if (!annotations.noAutoRetry && isEfdSuiteAdmissionAllowed &&
166
- isEarlyFlakeDetectionTest(testSuite, testName)) {
167
- task.retry = 0
168
- task.repeats = earlyFlakeDetectionRetries
169
- task.meta.__ddTestOptEfdRetries = earlyFlakeDetectionRetries
104
+ if (attemptIndex > 0) {
105
+ recordTestOptimizationStatus(task, attemptIndex - 1)
170
106
  }
171
- configureDynamicAtr(task)
172
- wrapRetryCondition(task)
173
- }
174
- }
175
- }
176
107
 
177
- /** @param {object} task */
178
- function isAutomaticRetryProject (task) {
179
- if (!flakyTestRetriesConfiguration) return false
180
- const projectName = task.file.projectName
181
- return projectName
182
- ? flakyTestRetriesConfiguration.projectNames.includes(projectName)
183
- : flakyTestRetriesConfiguration.includesUnnamedProject
184
- }
185
-
186
- /**
187
- * Stops Datadog-managed retries at the initial attempt's duration budget, after the complete lifecycle.
188
- *
189
- * @param {object} task
190
- */
191
- function configureDynamicAtr (task) {
192
- if (!dynamicAtrRetryPolicy || !flakyTestRetriesConfiguration) return
193
- const projectName = task.file.projectName
194
- const isManagedProject = projectName
195
- ? flakyTestRetriesConfiguration.projectNames.includes(projectName)
196
- : flakyTestRetriesConfiguration.includesUnnamedProject
197
- if (!isManagedProject || !task.retry?.__ddTestOptAtr || task.retry.count <= 0) return
198
-
199
- task.retry = {
200
- ...task.retry,
201
- condition () {
202
- // AroundEach fixture teardown can fail after onTestFinished recorded the attempt's errors.
203
- recordRetryErrorCount(task)
204
- if (task.meta.__ddTestOptAtrRetries === undefined) {
205
- const executionStart = dynamicAtrExecutionStartByTask.get(task) ?? task.result.startTime - timeOrigin
206
- const duration = now() - executionStart
207
- task.meta.__ddTestOptAtrRetries = dynamicAtrRetryPolicy.find(
208
- ({ durationLimitMs }) => durationLimitMs === undefined || duration <= durationLimitMs
209
- ).retryCount
108
+ if (!isAttemptToFixTest && !annotations.mustFail && disabledTests[testSuite]?.[testName]) {
109
+ skip('Skipped by Datadog Test Optimization')
110
+ } else if (isAttemptToFixTest && attemptIndex > 0) {
111
+ task.result.state = 'run'
112
+ } else if (isEarlyFlakeDetectionTestAttempt) {
113
+ const isSkippedRepeat = prepareEarlyFlakeDetectionAttempt(task, attemptIndex, skip)
114
+ if (!isSkippedRepeat && attemptIndex > 0) {
115
+ task.result.state = 'run'
116
+ }
210
117
  }
211
- const retryIndex = retryAttemptIndexByTask.get(task)?.index ?? task.result.retryCount
212
- return retryIndex < task.meta.__ddTestOptAtrRetries
213
- },
214
- }
215
- }
216
118
 
217
- function getNextAttemptIndex (task) {
218
- const attemptIndex = nextAttemptIndexByTask.get(task) || 0
219
- nextAttemptIndexByTask.set(task, attemptIndex + 1)
220
- task.meta.__ddTestOptCurrentAttemptIndex = attemptIndex
119
+ prepareRumCorrelation(task, attemptIndex)
120
+
121
+ onTestFinished(() => {
122
+ recordTestAttemptTiming(task, attemptIndex, attemptStart)
123
+ recordRetryErrorCount(task)
124
+ if (isEarlyFlakeDetectionTestAttempt || isQuarantinedTest ||
125
+ (isAttemptToFixTest && attemptIndex === getFinalAttemptIndex(task))) {
126
+ if (isAttemptToFixTest || isEarlyFlakeDetectionTestAttempt) {
127
+ recordTestOptimizationStatus(task, attemptIndex, attemptIndex === getFinalAttemptIndex(task))
128
+ }
129
+ switchQuarantinedFinalFailure(task)
130
+ }
131
+ finishRumCorrelation(task, attemptIndex)
132
+ })
133
+ })
221
134
 
222
- const repeatCount = task.result?.repeatCount || 0
223
- const retryAttempt = retryAttemptIndexByTask.get(task)
224
- const retryAttemptIndex = retryAttempt?.repeatCount === repeatCount ? retryAttempt.index + 1 : 0
225
- retryAttemptIndexByTask.set(task, {
226
- index: retryAttemptIndex,
227
- repeatCount,
228
- })
135
+ afterEach(function ({ task }) {
136
+ const attemptIndex = task.meta.__ddTestOptCurrentAttemptIndex
137
+ const restoredEarlyFlakeDetectionResult = restoreEarlyFlakeDetectionSkippedResult(task)
138
+ if (!restoredEarlyFlakeDetectionResult && attemptIndex === getFinalAttemptIndex(task)) {
139
+ recordTestOptimizationStatus(task, attemptIndex)
140
+ }
141
+ if (!restoredEarlyFlakeDetectionResult) {
142
+ switchQuarantinedFinalFailure(task)
143
+ }
144
+ })
145
+ }
229
146
 
230
- return attemptIndex
231
- }
147
+ function applyExecutionChanges (suite, isEfdSuiteAdmissionAllowed) {
148
+ const tasks = suite?.tasks
149
+ if (tasks) {
150
+ for (const task of tasks) {
151
+ if (task.type === 'suite') {
152
+ applyExecutionChanges(task, isEfdSuiteAdmissionAllowed)
153
+ continue
154
+ }
232
155
 
233
- /**
234
- * Sets the RUM correlation cookie for a sequential browser test attempt.
235
- *
236
- * @param {object} task
237
- * @param {number} attemptIndex
238
- */
239
- function prepareRumCorrelation (task, attemptIndex) {
240
- // A per-origin cookie cannot identify overlapping attempts without racing.
241
- if (
242
- !isRumCorrelationEnabled || isConcurrentTask(task) ||
243
- typeof window === 'undefined' ||
244
- typeof document === 'undefined' ||
245
- typeof rumTestExecutionIdCookieName !== 'string'
246
- ) {
247
- return
156
+ const testSuite = getTestSuite(task)
157
+ const testName = getTestName(task)
158
+ const annotations = task.meta?.__ddTestOptAnnotations || {}
159
+ if (annotations.noAutoRetry && !annotations.hasFrameworkRetry &&
160
+ (task.retry?.__ddTestOptAtr || isAutomaticRetryProject(task))) {
161
+ task.retry = 0
162
+ }
163
+ if (attemptToFixTests[testSuite]?.[testName] && !annotations.noAutoRetry) {
164
+ task.retry = 0
165
+ task.repeats = attemptToFixRetries
166
+ task.meta.__ddTestOptAtfRetries = attemptToFixRetries
167
+ } else if (disabledTests[testSuite]?.[testName] && !annotations.mustFail) {
168
+ task.mode = 'skip'
169
+ } else if (!annotations.noAutoRetry && isEfdSuiteAdmissionAllowed &&
170
+ isEarlyFlakeDetectionTest(testSuite, testName)) {
171
+ task.retry = 0
172
+ task.repeats = earlyFlakeDetectionRetries
173
+ task.meta.__ddTestOptEfdRetries = earlyFlakeDetectionRetries
174
+ }
175
+ configureDynamicAtr(task)
176
+ wrapRetryCondition(task)
177
+ }
178
+ }
248
179
  }
249
180
 
250
- const testExecutionId = generateTestExecutionId()
251
- if (
252
- !testExecutionId ||
253
- usedRumTestExecutionIds.has(testExecutionId) ||
254
- !setRumCorrelationCookie(testExecutionId)
255
- ) {
256
- return
181
+ /** @param {object} task */
182
+ function isAutomaticRetryProject (task) {
183
+ if (!flakyTestRetriesConfiguration) return false
184
+ const projectName = task.file.projectName
185
+ return projectName
186
+ ? flakyTestRetriesConfiguration.projectNames.includes(projectName)
187
+ : flakyTestRetriesConfiguration.includesUnnamedProject
188
+ }
189
+
190
+ /**
191
+ * Stops Datadog-managed retries at the initial attempt's duration budget, after the complete lifecycle.
192
+ *
193
+ * @param {object} task
194
+ */
195
+ function configureDynamicAtr (task) {
196
+ if (!dynamicAtrRetryPolicy || !flakyTestRetriesConfiguration) return
197
+ const projectName = task.file.projectName
198
+ const isManagedProject = projectName
199
+ ? flakyTestRetriesConfiguration.projectNames.includes(projectName)
200
+ : flakyTestRetriesConfiguration.includesUnnamedProject
201
+ if (!isManagedProject || !task.retry?.__ddTestOptAtr || task.retry.count <= 0) return
202
+
203
+ task.retry = {
204
+ ...task.retry,
205
+ condition () {
206
+ // AroundEach fixture teardown can fail after onTestFinished recorded the attempt's errors.
207
+ recordRetryErrorCount(task)
208
+ if (task.meta.__ddTestOptAtrRetries === undefined) {
209
+ const executionStart = dynamicAtrExecutionStartByTask.get(task) ?? task.result.startTime - timeOrigin
210
+ const duration = now() - executionStart
211
+ task.meta.__ddTestOptAtrRetries = dynamicAtrRetryPolicy.find(
212
+ ({ durationLimitMs }) => durationLimitMs === undefined || duration <= durationLimitMs
213
+ ).retryCount
214
+ }
215
+ const retryIndex = retryAttemptIndexByTask.get(task)?.index ?? task.result.retryCount
216
+ return retryIndex < task.meta.__ddTestOptAtrRetries
217
+ },
218
+ }
257
219
  }
258
220
 
259
- usedRumTestExecutionIds.add(testExecutionId)
260
- task.meta.__ddTestOptRumTestExecutionIds ||= []
261
- task.meta.__ddTestOptRumTestExecutionIds[attemptIndex] = testExecutionId
262
- recordRumActivity(task, attemptIndex)
263
- }
264
-
265
- /**
266
- * Records whether RUM was active and clears the attempt cookie.
267
- *
268
- * @param {object} task
269
- * @param {number} attemptIndex
270
- */
271
- function finishRumCorrelation (task, attemptIndex) {
272
- const testExecutionId = task.meta.__ddTestOptRumTestExecutionIds?.[attemptIndex]
273
- if (!testExecutionId) return
274
-
275
- recordRumActivity(task, attemptIndex)
276
- clearRumCorrelationCookie(testExecutionId)
277
- }
278
-
279
- /**
280
- * Retains evidence that RUM was active at any point observed during the attempt.
281
- *
282
- * @param {object} task
283
- * @param {number} attemptIndex
284
- */
285
- function recordRumActivity (task, attemptIndex) {
286
- if (!getIsRumActive(getRum())) return
287
-
288
- task.meta.__ddTestOptRumActive ||= []
289
- task.meta.__ddTestOptRumActive[attemptIndex] = true
290
- }
291
-
292
- /**
293
- * Returns the RUM public API without letting application-defined accessors fail a test.
294
- *
295
- * @returns {object|undefined}
296
- */
297
- function getRum () {
298
- try {
299
- return window.DD_RUM
300
- } catch {}
301
- }
221
+ function getNextAttemptIndex (task) {
222
+ const attemptIndex = nextAttemptIndexByTask.get(task) || 0
223
+ nextAttemptIndexByTask.set(task, attemptIndex + 1)
224
+ task.meta.__ddTestOptCurrentAttemptIndex = attemptIndex
302
225
 
303
- /**
304
- * Returns whether the current RUM session is active.
305
- *
306
- * @param {object|undefined} rum
307
- */
308
- function getIsRumActive (rum) {
309
- if (!rum || typeof rum.getInternalContext !== 'function') return false
226
+ const repeatCount = task.result?.repeatCount || 0
227
+ const retryAttempt = retryAttemptIndexByTask.get(task)
228
+ const retryAttemptIndex = retryAttempt?.repeatCount === repeatCount ? retryAttempt.index + 1 : 0
229
+ retryAttemptIndexByTask.set(task, {
230
+ index: retryAttemptIndex,
231
+ repeatCount,
232
+ })
310
233
 
311
- try {
312
- return !!rum.getInternalContext()
313
- } catch {
314
- return false
234
+ return attemptIndex
315
235
  }
316
- }
317
236
 
318
- /**
319
- * Returns whether a task or any containing suite is concurrent.
320
- *
321
- * @param {object} task
322
- */
323
- function isConcurrentTask (task) {
324
- let currentTask = task
325
- while (currentTask) {
326
- if (currentTask.concurrent === true) return true
327
- currentTask = currentTask.suite
328
- }
329
- return false
330
- }
237
+ /**
238
+ * Sets the RUM correlation cookie for a sequential browser test attempt.
239
+ *
240
+ * @param {object} task
241
+ * @param {number} attemptIndex
242
+ */
243
+ function prepareRumCorrelation (task, attemptIndex) {
244
+ // A per-origin cookie cannot identify overlapping attempts without racing.
245
+ if (
246
+ !isRumCorrelationEnabled || isConcurrentTask(task) ||
247
+ typeof window === 'undefined' ||
248
+ typeof document === 'undefined' ||
249
+ typeof rumTestExecutionIdCookieName !== 'string'
250
+ ) {
251
+ return
252
+ }
331
253
 
332
- /**
333
- * Generates a positive 63-bit decimal test execution ID.
334
- *
335
- * @returns {string|undefined}
336
- */
337
- function generateTestExecutionId () {
338
- // This setup file executes in a browser even though lint validates it against the package's Node.js target.
339
- // eslint-disable-next-line n/no-unsupported-features/node-builtins
340
- if (typeof globalThis.crypto?.getRandomValues !== 'function') return
254
+ const testExecutionId = generateTestExecutionId()
255
+ if (
256
+ !testExecutionId ||
257
+ usedRumTestExecutionIds.has(testExecutionId) ||
258
+ !setRumCorrelationCookie(testExecutionId)
259
+ ) {
260
+ return
261
+ }
341
262
 
342
- const words = new Uint32Array(2)
343
- try {
263
+ usedRumTestExecutionIds.add(testExecutionId)
264
+ task.meta.__ddTestOptRumTestExecutionIds ||= []
265
+ task.meta.__ddTestOptRumTestExecutionIds[attemptIndex] = testExecutionId
266
+ recordRumActivity(task, attemptIndex)
267
+ }
268
+
269
+ /**
270
+ * Records whether RUM was active and clears the attempt cookie.
271
+ *
272
+ * @param {object} task
273
+ * @param {number} attemptIndex
274
+ */
275
+ function finishRumCorrelation (task, attemptIndex) {
276
+ const testExecutionId = task.meta.__ddTestOptRumTestExecutionIds?.[attemptIndex]
277
+ if (!testExecutionId) return
278
+
279
+ recordRumActivity(task, attemptIndex)
280
+ clearRumCorrelationCookie(testExecutionId)
281
+ }
282
+
283
+ /**
284
+ * Generates a positive 63-bit decimal test execution ID.
285
+ *
286
+ * @returns {string|undefined}
287
+ */
288
+ function generateTestExecutionId () {
289
+ // This setup file executes in a browser even though lint validates it against the package's Node.js target.
344
290
  // eslint-disable-next-line n/no-unsupported-features/node-builtins
345
- globalThis.crypto.getRandomValues(words)
346
- } catch {
347
- return
348
- }
291
+ if (typeof globalThis.crypto?.getRandomValues !== 'function') return
349
292
 
350
- words[0] &= 0x7F_FF_FF_FF
351
- if (words[0] === 0 && words[1] === 0) return
293
+ const words = new Uint32Array(2)
294
+ try {
295
+ // eslint-disable-next-line n/no-unsupported-features/node-builtins
296
+ globalThis.crypto.getRandomValues(words)
297
+ } catch {
298
+ return
299
+ }
352
300
 
353
- return ((BigInt(words[0]) << 32n) | BigInt(words[1])).toString(10)
354
- }
301
+ words[0] &= 0x7F_FF_FF_FF
302
+ if (words[0] === 0 && words[1] === 0) return
355
303
 
356
- /**
357
- * Sets and verifies the RUM correlation cookie for the current origin.
358
- *
359
- * @param {string} testExecutionId
360
- */
361
- function setRumCorrelationCookie (testExecutionId) {
362
- try {
363
- // eslint-disable-next-line unicorn/no-document-cookie
364
- document.cookie = `${rumTestExecutionIdCookieName}=${testExecutionId}; path=/`
365
- return getRumCorrelationCookie() === testExecutionId
366
- } catch {
367
- return false
304
+ return ((BigInt(words[0]) << 32n) | BigInt(words[1])).toString(10)
368
305
  }
369
- }
370
306
 
371
- /**
372
- * Clears the RUM correlation cookie if it still belongs to this attempt.
373
- *
374
- * @param {string} testExecutionId
375
- */
376
- function clearRumCorrelationCookie (testExecutionId) {
377
- try {
378
- if (getRumCorrelationCookie() === testExecutionId) {
307
+ /**
308
+ * Sets and verifies the RUM correlation cookie for the current origin.
309
+ *
310
+ * @param {string} testExecutionId
311
+ */
312
+ function setRumCorrelationCookie (testExecutionId) {
313
+ try {
379
314
  // eslint-disable-next-line unicorn/no-document-cookie
380
- document.cookie = `${rumTestExecutionIdCookieName}=; path=/; max-age=0`
315
+ document.cookie = `${rumTestExecutionIdCookieName}=${testExecutionId}; path=/`
316
+ return getRumCorrelationCookie() === testExecutionId
317
+ } catch {
318
+ return false
381
319
  }
382
- } catch {}
383
- }
320
+ }
384
321
 
385
- /**
386
- * Returns the current RUM correlation cookie value.
387
- *
388
- * @returns {string|undefined}
389
- */
390
- function getRumCorrelationCookie () {
391
- const prefix = `${rumTestExecutionIdCookieName}=`
392
- for (const cookie of document.cookie.split(';')) {
393
- const normalizedCookie = cookie.trim()
394
- if (normalizedCookie.startsWith(prefix)) {
395
- return normalizedCookie.slice(prefix.length)
322
+ /**
323
+ * Clears the RUM correlation cookie if it still belongs to this attempt.
324
+ *
325
+ * @param {string} testExecutionId
326
+ */
327
+ function clearRumCorrelationCookie (testExecutionId) {
328
+ try {
329
+ if (getRumCorrelationCookie() === testExecutionId) {
330
+ // eslint-disable-next-line unicorn/no-document-cookie
331
+ document.cookie = `${rumTestExecutionIdCookieName}=; path=/; max-age=0`
332
+ }
333
+ } catch {}
334
+ }
335
+
336
+ /**
337
+ * Returns the current RUM correlation cookie value.
338
+ *
339
+ * @returns {string|undefined}
340
+ */
341
+ function getRumCorrelationCookie () {
342
+ const prefix = `${rumTestExecutionIdCookieName}=`
343
+ for (const cookie of document.cookie.split(';')) {
344
+ const normalizedCookie = cookie.trim()
345
+ if (normalizedCookie.startsWith(prefix)) {
346
+ return normalizedCookie.slice(prefix.length)
347
+ }
396
348
  }
397
349
  }
398
- }
399
350
 
400
- function recordTestOptimizationStatus (task, attemptIndex = task.result?.repeatCount || 0, onlyIfNewErrors = false) {
401
- const testSuite = getTestSuite(task)
402
- const testName = getTestName(task)
351
+ function recordTestOptimizationStatus (task, attemptIndex = task.result?.repeatCount || 0, onlyIfNewErrors = false) {
352
+ const testSuite = getTestSuite(task)
353
+ const testName = getTestName(task)
403
354
 
404
- if (attemptToFixTests[testSuite]?.[testName] && !task.meta?.__ddTestOptAnnotations?.noAutoRetry) {
405
- recordAttemptToFixStatus(task, attemptIndex, onlyIfNewErrors)
406
- } else if (isEarlyFlakeDetectionTask(task)) {
407
- recordEarlyFlakeDetectionStatus(task, attemptIndex, onlyIfNewErrors)
408
- } else if (task.repeats > 0) {
409
- recordManualRepeatStatus(task, attemptIndex)
355
+ if (attemptToFixTests[testSuite]?.[testName] && !task.meta?.__ddTestOptAnnotations?.noAutoRetry) {
356
+ recordAttemptToFixStatus(task, attemptIndex, onlyIfNewErrors)
357
+ } else if (isEarlyFlakeDetectionTask(task)) {
358
+ recordEarlyFlakeDetectionStatus(task, attemptIndex, onlyIfNewErrors)
359
+ } else if (task.repeats > 0) {
360
+ recordManualRepeatStatus(task, attemptIndex)
361
+ }
410
362
  }
411
- }
412
363
 
413
- function recordAttemptToFixStatus (task, attemptIndex, onlyIfNewErrors) {
414
- if (onlyIfNewErrors && !hasNewErrors(task.meta.__ddTestOptAtfErrorCounts, attemptIndex, task)) {
415
- return
416
- }
364
+ function recordEarlyFlakeDetectionStatus (task, attemptIndex, onlyIfNewErrors) {
365
+ if (restoreEarlyFlakeDetectionSkippedResult(task)) {
366
+ return
367
+ }
417
368
 
418
- task.meta.__ddTestOptAtfStatuses ||= []
419
- task.meta.__ddTestOptAtfErrorCounts ||= []
420
- task.meta.__ddTestOptAtfStatuses[attemptIndex] = getAttemptStatus(
421
- task,
422
- task.meta.__ddTestOptAtfErrorCounts,
423
- attemptIndex
424
- )
425
- task.meta.__ddTestOptAtfErrorCounts[attemptIndex] = task.result?.errors?.length || 0
369
+ const retryCount = earlyFlakeDetectionRetriesByTask.get(task)
370
+ if (retryCount !== undefined && attemptIndex > retryCount) {
371
+ return
372
+ }
426
373
 
427
- if (
428
- attemptIndex === getAttemptToFixRetryCount(task) &&
429
- task.meta.__ddTestOptAtfStatuses.includes('fail') &&
430
- task.result?.state === 'pass'
431
- ) {
432
- task.result.state = 'fail'
433
- }
434
- }
374
+ if (onlyIfNewErrors && !hasNewErrors(task.meta.__ddTestOptEfdErrorCounts, attemptIndex, task)) {
375
+ return
376
+ }
435
377
 
436
- function recordEarlyFlakeDetectionStatus (task, attemptIndex, onlyIfNewErrors) {
437
- if (restoreEarlyFlakeDetectionSkippedResult(task)) {
438
- return
439
- }
378
+ // onTestFinished runs before aroundEach fixture teardown. Select the budget
379
+ // when the next attempt records the completed attempt instead.
380
+ const isCompletedAttempt = attemptIndex < task.meta.__ddTestOptCurrentAttemptIndex
381
+ if (isCompletedAttempt && !earlyFlakeDetectionRetriesByTask.has(task)) {
382
+ const retryCount = getEarlyFlakeDetectionRetryCount(task)
383
+ earlyFlakeDetectionRetriesByTask.set(task, retryCount)
384
+ task.repeats = retryCount
385
+ task.meta.__ddTestOptEfdRetries = retryCount
386
+ if (retryCount === 0) {
387
+ task.meta.__ddTestOptEfdAbortReason = 'slow'
388
+ }
389
+ }
440
390
 
441
- const retryCount = earlyFlakeDetectionRetriesByTask.get(task)
442
- if (retryCount !== undefined && attemptIndex > retryCount) {
443
- return
391
+ task.meta.__ddTestOptEfdStatuses ||= []
392
+ task.meta.__ddTestOptEfdErrorCounts ||= []
393
+ task.meta.__ddTestOptEfdStatuses[attemptIndex] = getAttemptStatus(
394
+ task,
395
+ task.meta.__ddTestOptEfdErrorCounts,
396
+ attemptIndex
397
+ )
398
+ task.meta.__ddTestOptEfdErrorCounts[attemptIndex] = task.result?.errors?.length || 0
399
+
400
+ // Vitest 5.0.3 retains failures across repeats. Defer EFD's overall failure until
401
+ // the last attempt, while keeping each attempt's actual outcome in the metadata.
402
+ if (attemptIndex < getEarlyFlakeDetectionRetryCountForTask(task) ||
403
+ task.meta.__ddTestOptEfdStatuses.includes('pass')) {
404
+ task.result.state = 'pass'
405
+ } else if (isCompletedAttempt) {
406
+ // A zero retry budget cancels repeats after we suppressed the initial failure.
407
+ task.result.state = 'fail'
408
+ markQuarantinedFailure(task)
409
+ }
444
410
  }
445
411
 
446
- if (onlyIfNewErrors && !hasNewErrors(task.meta.__ddTestOptEfdErrorCounts, attemptIndex, task)) {
447
- return
448
- }
412
+ /**
413
+ * Records the wall-clock start and elapsed time for one retry or repeat execution.
414
+ *
415
+ * @param {object} task
416
+ * @param {number} attemptIndex
417
+ * @param {number} attemptStart
418
+ */
419
+ function recordTestAttemptTiming (task, attemptIndex, attemptStart) {
420
+ task.meta.__ddTestOptAttemptStartTimes ||= []
421
+ task.meta.__ddTestOptAttemptDurations ||= []
422
+ task.meta.__ddTestOptAttemptStartTimes[attemptIndex] = timeOrigin + attemptStart
423
+ task.meta.__ddTestOptAttemptDurations[attemptIndex] = now() - attemptStart
424
+ }
425
+
426
+ /**
427
+ * Wraps Vitest's retry condition so final-attempt handling follows the condition's actual result.
428
+ *
429
+ * @param {object} task
430
+ */
431
+ function wrapRetryCondition (task) {
432
+ if (typeof task.retry !== 'object' || !task.retry?.condition || getRetryLimit(task) === 0) return
433
+
434
+ const condition = task.retry.condition
435
+ task.retry = {
436
+ ...task.retry,
437
+ condition (error) {
438
+ let shouldRetry = false
439
+ if (condition instanceof RegExp) {
440
+ shouldRetry = condition.test(error?.message || '')
441
+ } else if (typeof condition === 'function') {
442
+ shouldRetry = condition(error)
443
+ }
449
444
 
450
- // onTestFinished runs before aroundEach fixture teardown. Select the budget
451
- // when the next attempt records the completed attempt instead.
452
- const isCompletedAttempt = attemptIndex < task.meta.__ddTestOptCurrentAttemptIndex
453
- if (isCompletedAttempt && !earlyFlakeDetectionRetriesByTask.has(task)) {
454
- const retryCount = getEarlyFlakeDetectionRetryCount(task)
455
- earlyFlakeDetectionRetriesByTask.set(task, retryCount)
456
- task.repeats = retryCount
457
- task.meta.__ddTestOptEfdRetries = retryCount
458
- if (retryCount === 0) {
459
- task.meta.__ddTestOptEfdAbortReason = 'slow'
445
+ if (!shouldRetry) {
446
+ const attemptIndex = task.meta.__ddTestOptCurrentAttemptIndex
447
+ recordTestOptimizationStatus(task, attemptIndex)
448
+ markQuarantinedFailure(task)
449
+ }
450
+ return shouldRetry
451
+ },
460
452
  }
461
453
  }
462
454
 
463
- task.meta.__ddTestOptEfdStatuses ||= []
464
- task.meta.__ddTestOptEfdErrorCounts ||= []
465
- task.meta.__ddTestOptEfdStatuses[attemptIndex] = getAttemptStatus(
466
- task,
467
- task.meta.__ddTestOptEfdErrorCounts,
468
- attemptIndex
469
- )
470
- task.meta.__ddTestOptEfdErrorCounts[attemptIndex] = task.result?.errors?.length || 0
455
+ function restoreEarlyFlakeDetectionSkippedResult (task) {
456
+ if (!task.meta.__ddTestOptEfdSkipCurrentAttempt) {
457
+ return false
458
+ }
471
459
 
472
- // Vitest 5.0.3 retains failures across repeats. Defer EFD's overall failure until
473
- // the last attempt, while keeping each attempt's actual outcome in the metadata.
474
- if (attemptIndex < getEarlyFlakeDetectionRetryCountForTask(task) ||
475
- task.meta.__ddTestOptEfdStatuses.includes('pass')) {
476
- task.result.state = 'pass'
477
- } else if (isCompletedAttempt) {
478
- // A zero retry budget cancels repeats after we suppressed the initial failure.
479
- task.result.state = 'fail'
480
- markQuarantinedFailure(task)
460
+ delete task.meta.__ddTestOptEfdSkipCurrentAttempt
461
+ const skippedResult = earlyFlakeDetectionSkippedResults.get(task)
462
+ if (skippedResult) {
463
+ task.result = skippedResult
464
+ earlyFlakeDetectionSkippedResults.delete(task)
465
+ }
466
+ return true
481
467
  }
482
- }
483
468
 
484
- function recordManualRepeatStatus (task, attemptIndex) {
485
- task.meta.__ddTestOptRepeatStatuses ||= []
486
- task.meta.__ddTestOptRepeatErrorCounts ||= []
487
- task.meta.__ddTestOptRepeatStatuses[attemptIndex] = getManualRepeatStatus(
488
- task,
489
- task.meta.__ddTestOptRepeatErrorCounts,
490
- attemptIndex
491
- )
492
- task.meta.__ddTestOptRepeatErrorCounts[attemptIndex] = task.result?.errors?.length || 0
493
- }
469
+ function getFinalAttemptIndex (task) {
470
+ const testSuite = getTestSuite(task)
471
+ const testName = getTestName(task)
494
472
 
495
- /**
496
- * Records cumulative errors at the end of each configured retry attempt.
497
- *
498
- * @param {object} task
499
- */
500
- function recordRetryErrorCount (task) {
501
- const retryLimit = getRetryLimit(task)
502
- if (retryLimit <= 0) return
473
+ if (attemptToFixTests[testSuite]?.[testName] && !task.meta?.__ddTestOptAnnotations?.noAutoRetry) {
474
+ return getAttemptToFixRetryCount(task)
475
+ }
476
+ if (isEarlyFlakeDetectionTask(task)) {
477
+ return getEarlyFlakeDetectionRetryCountForTask(task)
478
+ }
503
479
 
504
- const retryCount = task.result?.retryCount || 0
505
- task.meta.__ddTestOptRetryErrorCounts ||= []
506
- task.meta.__ddTestOptRetryErrorCounts[retryCount] = task.result?.errors?.length || 0
507
- }
480
+ const attemptIndex = task.meta.__ddTestOptCurrentAttemptIndex
481
+ const repeatCount = task.result?.repeatCount || 0
482
+ const repeatLimit = task.repeats || 0
483
+ const retryAttemptIndex = retryAttemptIndexByTask.get(task)?.index || 0
484
+ const retryLimit = getRetryLimit(task)
485
+ const retriesRemaining = task.result?.state === 'fail' || task.result?.state === 'run'
486
+ ? Math.max(retryLimit - retryAttemptIndex, 0)
487
+ : 0
488
+ const repeatsRemaining = Math.max(repeatLimit - repeatCount, 0)
508
489
 
509
- /**
510
- * Records the wall-clock start and elapsed time for one retry or repeat execution.
511
- *
512
- * @param {object} task
513
- * @param {number} attemptIndex
514
- * @param {number} attemptStart
515
- */
516
- function recordTestAttemptTiming (task, attemptIndex, attemptStart) {
517
- task.meta.__ddTestOptAttemptStartTimes ||= []
518
- task.meta.__ddTestOptAttemptDurations ||= []
519
- task.meta.__ddTestOptAttemptStartTimes[attemptIndex] = timeOrigin + attemptStart
520
- task.meta.__ddTestOptAttemptDurations[attemptIndex] = now() - attemptStart
521
- }
490
+ return attemptIndex + retriesRemaining + (repeatsRemaining * (retryLimit + 1))
491
+ }
522
492
 
523
- /**
524
- * Returns the configured retry count for numeric and object-form retry options.
525
- *
526
- * @param {object} task
527
- */
528
- function getRetryLimit (task) {
529
- return task.meta.__ddTestOptAtrRetries ?? (typeof task.retry === 'number' ? task.retry : task.retry?.count || 0)
530
- }
493
+ function switchQuarantinedFinalFailure (task) {
494
+ const testSuite = getTestSuite(task)
495
+ const testName = getTestName(task)
496
+ if (
497
+ !quarantinedTests[testSuite]?.[testName] ||
498
+ task.meta?.__ddTestOptAnnotations?.mustFail ||
499
+ (attemptToFixTests[testSuite]?.[testName] && !task.meta?.__ddTestOptAnnotations?.noAutoRetry) ||
500
+ task.result?.state !== 'fail'
501
+ ) {
502
+ return
503
+ }
531
504
 
532
- /**
533
- * Wraps Vitest's retry condition so final-attempt handling follows the condition's actual result.
534
- *
535
- * @param {object} task
536
- */
537
- function wrapRetryCondition (task) {
538
- if (typeof task.retry !== 'object' || !task.retry?.condition || getRetryLimit(task) === 0) return
539
-
540
- const condition = task.retry.condition
541
- task.retry = {
542
- ...task.retry,
543
- condition (error) {
544
- let shouldRetry = false
545
- if (condition instanceof RegExp) {
546
- shouldRetry = condition.test(error?.message || '')
547
- } else if (typeof condition === 'function') {
548
- shouldRetry = condition(error)
549
- }
505
+ // Finish the retries in this repetition before suppressing its failure. A later
506
+ // repetition cannot undo a failure that Vitest has already aggregated.
507
+ const retryAttemptIndex = retryAttemptIndexByTask.get(task)?.index || 0
508
+ if (retryAttemptIndex < getRetryLimit(task)) {
509
+ return
510
+ }
550
511
 
551
- if (!shouldRetry) {
552
- const attemptIndex = task.meta.__ddTestOptCurrentAttemptIndex
553
- recordTestOptimizationStatus(task, attemptIndex)
554
- markQuarantinedFailure(task)
555
- }
556
- return shouldRetry
557
- },
512
+ markQuarantinedFailure(task)
558
513
  }
559
- }
560
514
 
561
- function restoreEarlyFlakeDetectionSkippedResult (task) {
562
- if (!task.meta.__ddTestOptEfdSkipCurrentAttempt) {
563
- return false
564
- }
515
+ /**
516
+ * Converts a quarantined failure into the passing runner state expected by Vitest.
517
+ *
518
+ * @param {object} task
519
+ */
520
+ function markQuarantinedFailure (task) {
521
+ const testSuite = getTestSuite(task)
522
+ const testName = getTestName(task)
523
+ if (
524
+ !quarantinedTests[testSuite]?.[testName] ||
525
+ task.meta?.__ddTestOptAnnotations?.mustFail ||
526
+ (attemptToFixTests[testSuite]?.[testName] && !task.meta?.__ddTestOptAnnotations?.noAutoRetry) ||
527
+ task.result?.state !== 'fail'
528
+ ) {
529
+ return
530
+ }
565
531
 
566
- delete task.meta.__ddTestOptEfdSkipCurrentAttempt
567
- const skippedResult = earlyFlakeDetectionSkippedResults.get(task)
568
- if (skippedResult) {
569
- task.result = skippedResult
570
- earlyFlakeDetectionSkippedResults.delete(task)
532
+ task.meta.__ddTestOptQuarantinedFailed = true
533
+ task.result.state = 'pass'
571
534
  }
572
- return true
573
- }
574
535
 
575
- function hasNewErrors (errorCounts, attemptIndex, task) {
576
- const recordedErrorCount = errorCounts?.[attemptIndex]
577
- const previousErrorCount = recordedErrorCount ?? getPreviousErrorCount(errorCounts, attemptIndex)
578
- return (task.result?.errors?.length || 0) > previousErrorCount
579
- }
536
+ function getEarlyFlakeDetectionRetryCountForTask (task) {
537
+ return earlyFlakeDetectionRetriesByTask.get(task) ?? task.meta.__ddTestOptEfdRetries ?? task.repeats
538
+ }
580
539
 
581
- function getFinalAttemptIndex (task) {
582
- const testSuite = getTestSuite(task)
583
- const testName = getTestName(task)
540
+ function prepareEarlyFlakeDetectionAttempt (task, attemptIndex, skip) {
541
+ if (attemptIndex === 0) {
542
+ earlyFlakeDetectionStartByTask.set(task, now())
543
+ return false
544
+ }
584
545
 
585
- if (attemptToFixTests[testSuite]?.[testName] && !task.meta?.__ddTestOptAnnotations?.noAutoRetry) {
586
- return getAttemptToFixRetryCount(task)
587
- }
588
- if (isEarlyFlakeDetectionTask(task)) {
589
- return getEarlyFlakeDetectionRetryCountForTask(task)
590
- }
546
+ let retryCount = earlyFlakeDetectionRetriesByTask.get(task)
547
+ if (retryCount === undefined) {
548
+ retryCount = getEarlyFlakeDetectionRetryCount(task)
549
+ earlyFlakeDetectionRetriesByTask.set(task, retryCount)
550
+ task.repeats = retryCount
551
+ task.meta.__ddTestOptEfdRetries = retryCount
552
+ if (retryCount === 0) {
553
+ task.meta.__ddTestOptEfdAbortReason = 'slow'
554
+ }
555
+ }
591
556
 
592
- const attemptIndex = task.meta.__ddTestOptCurrentAttemptIndex
593
- const repeatCount = task.result?.repeatCount || 0
594
- const repeatLimit = task.repeats || 0
595
- const retryAttemptIndex = retryAttemptIndexByTask.get(task)?.index || 0
596
- const retryLimit = getRetryLimit(task)
597
- const retriesRemaining = task.result?.state === 'fail' || task.result?.state === 'run'
598
- ? Math.max(retryLimit - retryAttemptIndex, 0)
599
- : 0
600
- const repeatsRemaining = Math.max(repeatLimit - repeatCount, 0)
557
+ if (attemptIndex <= retryCount) {
558
+ earlyFlakeDetectionStartByTask.set(task, now())
559
+ return false
560
+ }
601
561
 
602
- return attemptIndex + retriesRemaining + (repeatsRemaining * (retryLimit + 1))
603
- }
562
+ const canReplaceTaskFn = canReplaceVitestTaskFn()
563
+ if (!canReplaceTaskFn && typeof skipVitestTask !== 'function') {
564
+ earlyFlakeDetectionStartByTask.set(task, now())
565
+ return false
566
+ }
604
567
 
605
- function switchQuarantinedFinalFailure (task) {
606
- const testSuite = getTestSuite(task)
607
- const testName = getTestName(task)
608
- if (
609
- !quarantinedTests[testSuite]?.[testName] ||
610
- task.meta?.__ddTestOptAnnotations?.mustFail ||
611
- (attemptToFixTests[testSuite]?.[testName] && !task.meta?.__ddTestOptAnnotations?.noAutoRetry) ||
612
- task.result?.state !== 'fail'
613
- ) {
614
- return
568
+ if (task.result) {
569
+ earlyFlakeDetectionSkippedResults.set(task, {
570
+ ...task.result,
571
+ errors: task.result.errors?.slice(),
572
+ })
573
+ }
574
+ task.meta.__ddTestOptEfdSkipCurrentAttempt = true
575
+ if (canReplaceTaskFn) {
576
+ replaceVitestTaskFn(task, noopTest)
577
+ } else {
578
+ skipVitestTask(skip)
579
+ }
580
+ return true
615
581
  }
616
582
 
617
- // Finish the retries in this repetition before suppressing its failure. A later
618
- // repetition cannot undo a failure that Vitest has already aggregated.
619
- const retryAttemptIndex = retryAttemptIndexByTask.get(task)?.index || 0
620
- if (retryAttemptIndex < getRetryLimit(task)) {
621
- return
583
+ function getEarlyFlakeDetectionRetryCount (task) {
584
+ const executionStart = earlyFlakeDetectionStartByTask.get(task)
585
+ const duration = executionStart === undefined ? task.result?.duration ?? 0 : now() - executionStart
586
+ for (const { durationLimitMs, retryCount } of earlyFlakeDetectionRetryPolicy.durationRetryCounts) {
587
+ if (duration < durationLimitMs) return retryCount
588
+ }
589
+ return 0
622
590
  }
623
591
 
624
- markQuarantinedFailure(task)
625
- }
592
+ /**
593
+ * Returns whether Vitest's private task function setter is available.
594
+ *
595
+ */
596
+ function canReplaceVitestTaskFn () {
597
+ return typeof setVitestTaskFn === 'function'
598
+ }
626
599
 
627
- /**
628
- * Converts a quarantined failure into the passing runner state expected by Vitest.
629
- *
630
- * @param {object} task
631
- */
632
- function markQuarantinedFailure (task) {
633
- const testSuite = getTestSuite(task)
634
- const testName = getTestName(task)
635
- if (
636
- !quarantinedTests[testSuite]?.[testName] ||
637
- task.meta?.__ddTestOptAnnotations?.mustFail ||
638
- (attemptToFixTests[testSuite]?.[testName] && !task.meta?.__ddTestOptAnnotations?.noAutoRetry) ||
639
- task.result?.state !== 'fail'
640
- ) {
641
- return
600
+ /**
601
+ * Replaces the function Vitest runs for a task.
602
+ *
603
+ * @param {object} task
604
+ * @param {(...args: unknown[]) => unknown} testFn
605
+ */
606
+ function replaceVitestTaskFn (task, testFn) {
607
+ setVitestTaskFn(task, testFn)
642
608
  }
643
609
 
644
- task.meta.__ddTestOptQuarantinedFailed = true
645
- task.result.state = 'pass'
646
- }
610
+ function isEarlyFlakeDetectionTest (testSuite, testName) {
611
+ if (!isEarlyFlakeDetectionEnabled || earlyFlakeDetectionRetries <= 0) return false
612
+ if (isModifiedTest(testSuite)) return true
613
+ const testsForSuite = knownTests[testSuite] || []
614
+ return !testsForSuite.includes(testName)
615
+ }
647
616
 
648
- function getAttemptToFixRetryCount (task) {
649
- return task.meta.__ddTestOptAtfRetries ?? task.repeats
650
- }
617
+ /**
618
+ * Returns suite admission data when a collected suite contains an EFD candidate.
619
+ *
620
+ * @param {object} suite
621
+ * @returns {{ hasNewTest: boolean, testSuite: string }|undefined}
622
+ */
623
+ function getEarlyFlakeDetectionSuiteCandidate (suite) {
624
+ const tasks = suite?.tasks
625
+ if (!tasks) return
651
626
 
652
- function getEarlyFlakeDetectionRetryCountForTask (task) {
653
- return earlyFlakeDetectionRetriesByTask.get(task) ?? task.meta.__ddTestOptEfdRetries ?? task.repeats
654
- }
627
+ let candidate
628
+ for (const task of tasks) {
629
+ if (task.type === 'suite') {
630
+ const nestedCandidate = getEarlyFlakeDetectionSuiteCandidate(task)
631
+ if (nestedCandidate) {
632
+ candidate ||= nestedCandidate
633
+ candidate.hasNewTest ||= nestedCandidate.hasNewTest
634
+ }
635
+ continue
636
+ }
655
637
 
656
- function getAttemptStatus (task, errorCounts, repeatCount) {
657
- const errorCount = task.result?.errors?.length || 0
658
- if (errorCount > getPreviousErrorCount(errorCounts, repeatCount)) {
659
- return 'fail'
660
- }
661
- return task.result?.state === 'fail' ? 'fail' : 'pass'
662
- }
638
+ if (task.mode === 'skip' || task.mode === 'todo') continue
663
639
 
664
- function getManualRepeatStatus (task, errorCounts, repeatCount) {
665
- const errorCount = task.result?.errors?.length || 0
666
- return errorCount > getPreviousErrorCount(errorCounts, repeatCount) ? 'fail' : 'pass'
667
- }
640
+ const testSuite = getTestSuite(task)
641
+ const testName = getTestName(task)
642
+ const annotations = task.meta?.__ddTestOptAnnotations || {}
643
+ if (
644
+ annotations.noAutoRetry ||
645
+ attemptToFixTests[testSuite]?.[testName] ||
646
+ (disabledTests[testSuite]?.[testName] && !annotations.mustFail) ||
647
+ !isEarlyFlakeDetectionTest(testSuite, testName)
648
+ ) {
649
+ continue
650
+ }
668
651
 
669
- function getPreviousErrorCount (errorCounts, repeatCount) {
670
- for (let index = repeatCount - 1; index >= 0; index--) {
671
- if (errorCounts[index] !== undefined) {
672
- return errorCounts[index]
652
+ candidate ||= {
653
+ hasNewTest: false,
654
+ testSuite,
655
+ }
656
+ candidate.hasNewTest ||= isNewTest(testSuite, testName)
673
657
  }
658
+ return candidate
674
659
  }
675
- return 0
676
- }
677
660
 
678
- function prepareEarlyFlakeDetectionAttempt (task, attemptIndex, skip) {
679
- if (attemptIndex === 0) {
680
- earlyFlakeDetectionStartByTask.set(task, now())
681
- return false
661
+ /**
662
+ * Returns whether a collected test is absent from the known-tests response.
663
+ *
664
+ * @param {string} testSuite
665
+ * @param {string} testName
666
+ */
667
+ function isNewTest (testSuite, testName) {
668
+ return !(knownTests[testSuite] || []).includes(testName)
682
669
  }
683
670
 
684
- let retryCount = earlyFlakeDetectionRetriesByTask.get(task)
685
- if (retryCount === undefined) {
686
- retryCount = getEarlyFlakeDetectionRetryCount(task)
687
- earlyFlakeDetectionRetriesByTask.set(task, retryCount)
688
- task.repeats = retryCount
689
- task.meta.__ddTestOptEfdRetries = retryCount
690
- if (retryCount === 0) {
691
- task.meta.__ddTestOptEfdAbortReason = 'slow'
692
- }
671
+ function isModifiedTest (testSuite) {
672
+ return modifiedFiles[testSuite]?.length > 0
693
673
  }
694
674
 
695
- if (attemptIndex <= retryCount) {
696
- earlyFlakeDetectionStartByTask.set(task, now())
697
- return false
675
+ function getTestSuite (task) {
676
+ const filepath = task.file.filepath
677
+ return testPropertiesByFilepath[filepath]?.testSuite ||
678
+ testPropertiesByFilepath[normalizePath(filepath)]?.testSuite ||
679
+ normalizePath(filepath)
698
680
  }
699
681
 
700
- const canReplaceTaskFn = canReplaceVitestTaskFn()
701
- if (!canReplaceTaskFn && typeof skipVitestTask !== 'function') {
702
- earlyFlakeDetectionStartByTask.set(task, now())
703
- return false
682
+ function getIsNoWorkerInitActive () {
683
+ try {
684
+ // eslint-disable-next-line eslint-rules/eslint-process-env
685
+ const value = process.env[VITEST_NO_WORKER_INIT_ACTIVE_ENV]
686
+ return value === '1' || value === 'true'
687
+ } catch {
688
+ return false
689
+ }
704
690
  }
705
691
 
706
- if (task.result) {
707
- earlyFlakeDetectionSkippedResults.set(task, {
708
- ...task.result,
709
- errors: task.result.errors?.slice(),
710
- })
711
- }
712
- task.meta.__ddTestOptEfdSkipCurrentAttempt = true
713
- if (canReplaceTaskFn) {
714
- replaceVitestTaskFn(task, noopTest)
715
- } else {
716
- skipVitestTask(skip)
692
+ function getProvidedContext () {
693
+ try {
694
+ return parseProvidedContextValue(inject('_ddVitestWorkerSetup'))
695
+ } catch {
696
+ try {
697
+ return parseProvidedContextValue(globalThis.__vitest_worker__.providedContext._ddVitestWorkerSetup)
698
+ } catch {
699
+ return {}
700
+ }
701
+ }
717
702
  }
718
- return true
719
- }
720
703
 
721
- function getEarlyFlakeDetectionRetryCount (task) {
722
- const executionStart = earlyFlakeDetectionStartByTask.get(task)
723
- const duration = executionStart === undefined ? task.result?.duration ?? 0 : now() - executionStart
724
- for (const { durationLimitMs, retryCount } of earlyFlakeDetectionRetryPolicy.durationRetryCounts) {
725
- if (duration < durationLimitMs) return retryCount
704
+ /**
705
+ * Restore context serialized to keep Vitest's inline browser bootstrap script valid.
706
+ *
707
+ * @param {object|string|undefined} value
708
+ * @returns {object}
709
+ */
710
+ function parseProvidedContextValue (value) {
711
+ if (typeof value !== 'string' || !value.startsWith(SERIALIZED_CONTEXT_PREFIX)) return value || {}
712
+
713
+ try {
714
+ return JSON.parse(value.slice(SERIALIZED_CONTEXT_PREFIX.length))
715
+ } catch {
716
+ return {}
717
+ }
726
718
  }
727
- return 0
728
719
  }
729
720
 
730
- function noopTest () {}
731
-
732
721
  /**
733
- * Returns whether Vitest's private task function setter is available.
722
+ * Returns the RUM public API without letting application-defined accessors fail a test.
734
723
  *
724
+ * @returns {object|undefined}
735
725
  */
736
- function canReplaceVitestTaskFn () {
737
- return typeof setVitestTaskFn === 'function'
726
+ function getRum () {
727
+ try {
728
+ return window.DD_RUM
729
+ } catch {}
738
730
  }
739
731
 
740
732
  /**
741
- * Replaces the function Vitest runs for a task.
733
+ * Returns whether the current RUM session is active.
742
734
  *
743
- * @param {object} task
744
- * @param {(...args: unknown[]) => unknown} testFn
735
+ * @param {object|undefined} rum
745
736
  */
746
- function replaceVitestTaskFn (task, testFn) {
747
- setVitestTaskFn(task, testFn)
748
- }
737
+ function getIsRumActive (rum) {
738
+ if (!rum || typeof rum.getInternalContext !== 'function') return false
749
739
 
750
- function isEarlyFlakeDetectionTest (testSuite, testName) {
751
- if (!isEarlyFlakeDetectionEnabled || earlyFlakeDetectionRetries <= 0) return false
752
- if (isModifiedTest(testSuite)) return true
753
- const testsForSuite = knownTests[testSuite] || []
754
- return !testsForSuite.includes(testName)
740
+ try {
741
+ return !!rum.getInternalContext()
742
+ } catch {
743
+ return false
744
+ }
755
745
  }
756
746
 
757
747
  /**
758
- * Returns whether Datadog admitted this task for EFD retries.
748
+ * Returns whether a task or any containing suite is concurrent.
759
749
  *
760
750
  * @param {object} task
761
751
  */
762
- function isEarlyFlakeDetectionTask (task) {
763
- return task.meta.__ddTestOptEfdRetries !== undefined
752
+ function isConcurrentTask (task) {
753
+ let currentTask = task
754
+ while (currentTask) {
755
+ if (currentTask.concurrent === true) return true
756
+ currentTask = currentTask.suite
757
+ }
758
+ return false
764
759
  }
765
760
 
766
761
  /**
767
- * Returns suite admission data when a collected suite contains an EFD candidate.
762
+ * Returns the configured retry count for numeric and object-form retry options.
768
763
  *
769
- * @param {object} suite
770
- * @returns {{ hasNewTest: boolean, testSuite: string }|undefined}
764
+ * @param {object} task
771
765
  */
772
- function getEarlyFlakeDetectionSuiteCandidate (suite) {
773
- const tasks = suite?.tasks
774
- if (!tasks) return
775
-
776
- let candidate
777
- for (const task of tasks) {
778
- if (task.type === 'suite') {
779
- const nestedCandidate = getEarlyFlakeDetectionSuiteCandidate(task)
780
- if (nestedCandidate) {
781
- candidate ||= nestedCandidate
782
- candidate.hasNewTest ||= nestedCandidate.hasNewTest
783
- }
784
- continue
785
- }
786
-
787
- if (task.mode === 'skip' || task.mode === 'todo') continue
766
+ function getRetryLimit (task) {
767
+ return task.meta.__ddTestOptAtrRetries ?? (typeof task.retry === 'number' ? task.retry : task.retry?.count || 0)
768
+ }
788
769
 
789
- const testSuite = getTestSuite(task)
790
- const testName = getTestName(task)
791
- const annotations = task.meta?.__ddTestOptAnnotations || {}
792
- if (
793
- annotations.noAutoRetry ||
794
- attemptToFixTests[testSuite]?.[testName] ||
795
- (disabledTests[testSuite]?.[testName] && !annotations.mustFail) ||
796
- !isEarlyFlakeDetectionTest(testSuite, testName)
797
- ) {
798
- continue
799
- }
770
+ function getAttemptToFixRetryCount (task) {
771
+ return task.meta.__ddTestOptAtfRetries ?? task.repeats
772
+ }
800
773
 
801
- candidate ||= {
802
- hasNewTest: false,
803
- testSuite,
774
+ function getPreviousErrorCount (errorCounts, repeatCount) {
775
+ for (let index = repeatCount - 1; index >= 0; index--) {
776
+ if (errorCounts[index] !== undefined) {
777
+ return errorCounts[index]
804
778
  }
805
- candidate.hasNewTest ||= isNewTest(testSuite, testName)
806
779
  }
807
- return candidate
780
+ return 0
808
781
  }
809
782
 
783
+ function noopTest () {}
784
+
810
785
  /**
811
- * Returns whether a collected test is absent from the known-tests response.
786
+ * Returns whether Datadog admitted this task for EFD retries.
812
787
  *
813
- * @param {string} testSuite
814
- * @param {string} testName
788
+ * @param {object} task
815
789
  */
816
- function isNewTest (testSuite, testName) {
817
- return !(knownTests[testSuite] || []).includes(testName)
818
- }
819
-
820
- function isModifiedTest (testSuite) {
821
- return modifiedFiles[testSuite]?.length > 0
822
- }
823
-
824
- function getTestSuite (task) {
825
- const filepath = task.file.filepath
826
- return testPropertiesByFilepath[filepath]?.testSuite ||
827
- testPropertiesByFilepath[normalizePath(filepath)]?.testSuite ||
828
- normalizePath(filepath)
790
+ function isEarlyFlakeDetectionTask (task) {
791
+ return task.meta.__ddTestOptEfdRetries !== undefined
829
792
  }
830
793
 
831
794
  function getTestName (task) {
@@ -846,40 +809,82 @@ function normalizePath (filepath) {
846
809
  return filepath.replaceAll('\\', '/')
847
810
  }
848
811
 
849
- function getIsNoWorkerInitActive () {
850
- try {
851
- // eslint-disable-next-line eslint-rules/eslint-process-env
852
- const value = process.env[VITEST_NO_WORKER_INIT_ACTIVE_ENV]
853
- return value === '1' || value === 'true'
854
- } catch {
855
- return false
856
- }
857
- }
812
+ /**
813
+ * Retains evidence that RUM was active at any point observed during the attempt.
814
+ *
815
+ * @param {object} task
816
+ * @param {number} attemptIndex
817
+ */
818
+ function recordRumActivity (task, attemptIndex) {
819
+ if (!getIsRumActive(getRum())) return
858
820
 
859
- function getProvidedContext () {
860
- try {
861
- return parseProvidedContextValue(inject('_ddVitestWorkerSetup'))
862
- } catch {
863
- try {
864
- return parseProvidedContextValue(globalThis.__vitest_worker__.providedContext._ddVitestWorkerSetup)
865
- } catch {
866
- return {}
867
- }
868
- }
821
+ task.meta.__ddTestOptRumActive ||= []
822
+ task.meta.__ddTestOptRumActive[attemptIndex] = true
869
823
  }
870
824
 
871
825
  /**
872
- * Restore context serialized to keep Vitest's inline browser bootstrap script valid.
826
+ * Records cumulative errors at the end of each configured retry attempt.
873
827
  *
874
- * @param {object|string|undefined} value
875
- * @returns {object}
828
+ * @param {object} task
876
829
  */
877
- function parseProvidedContextValue (value) {
878
- if (typeof value !== 'string' || !value.startsWith(SERIALIZED_CONTEXT_PREFIX)) return value || {}
830
+ function recordRetryErrorCount (task) {
831
+ const retryLimit = getRetryLimit(task)
832
+ if (retryLimit <= 0) return
879
833
 
880
- try {
881
- return JSON.parse(value.slice(SERIALIZED_CONTEXT_PREFIX.length))
882
- } catch {
883
- return {}
834
+ const retryCount = task.result?.retryCount || 0
835
+ task.meta.__ddTestOptRetryErrorCounts ||= []
836
+ task.meta.__ddTestOptRetryErrorCounts[retryCount] = task.result?.errors?.length || 0
837
+ }
838
+
839
+ function hasNewErrors (errorCounts, attemptIndex, task) {
840
+ const recordedErrorCount = errorCounts?.[attemptIndex]
841
+ const previousErrorCount = recordedErrorCount ?? getPreviousErrorCount(errorCounts, attemptIndex)
842
+ return (task.result?.errors?.length || 0) > previousErrorCount
843
+ }
844
+
845
+ function getAttemptStatus (task, errorCounts, repeatCount) {
846
+ const errorCount = task.result?.errors?.length || 0
847
+ if (errorCount > getPreviousErrorCount(errorCounts, repeatCount)) {
848
+ return 'fail'
884
849
  }
850
+ return task.result?.state === 'fail' ? 'fail' : 'pass'
851
+ }
852
+
853
+ function getManualRepeatStatus (task, errorCounts, repeatCount) {
854
+ const errorCount = task.result?.errors?.length || 0
855
+ return errorCount > getPreviousErrorCount(errorCounts, repeatCount) ? 'fail' : 'pass'
856
+ }
857
+
858
+ function recordAttemptToFixStatus (task, attemptIndex, onlyIfNewErrors) {
859
+ if (onlyIfNewErrors && !hasNewErrors(task.meta.__ddTestOptAtfErrorCounts, attemptIndex, task)) {
860
+ return
861
+ }
862
+
863
+ task.meta.__ddTestOptAtfStatuses ||= []
864
+ task.meta.__ddTestOptAtfErrorCounts ||= []
865
+ task.meta.__ddTestOptAtfStatuses[attemptIndex] = getAttemptStatus(
866
+ task,
867
+ task.meta.__ddTestOptAtfErrorCounts,
868
+ attemptIndex
869
+ )
870
+ task.meta.__ddTestOptAtfErrorCounts[attemptIndex] = task.result?.errors?.length || 0
871
+
872
+ if (
873
+ attemptIndex === getAttemptToFixRetryCount(task) &&
874
+ task.meta.__ddTestOptAtfStatuses.includes('fail') &&
875
+ task.result?.state === 'pass'
876
+ ) {
877
+ task.result.state = 'fail'
878
+ }
879
+ }
880
+
881
+ function recordManualRepeatStatus (task, attemptIndex) {
882
+ task.meta.__ddTestOptRepeatStatuses ||= []
883
+ task.meta.__ddTestOptRepeatErrorCounts ||= []
884
+ task.meta.__ddTestOptRepeatStatuses[attemptIndex] = getManualRepeatStatus(
885
+ task,
886
+ task.meta.__ddTestOptRepeatErrorCounts,
887
+ attemptIndex
888
+ )
889
+ task.meta.__ddTestOptRepeatErrorCounts[attemptIndex] = task.result?.errors?.length || 0
885
890
  }