dd-trace 6.22.0 → 6.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/LICENSE-3rdparty.csv +0 -1
  2. package/ci/cypress/support.js +15 -1
  3. package/ci/diagnose.js +4 -4
  4. package/ci/test-annotations.d.ts +5 -0
  5. package/ci/test-annotations.js +5 -0
  6. package/ci/test-optimization-validation/approval-artifacts.js +2 -2
  7. package/ci/test-optimization-validation/approval.js +2 -2
  8. package/ci/test-optimization-validation/artifact-id.js +2 -3
  9. package/ci/test-optimization-validation/ci-package-scripts.js +1 -1
  10. package/ci/test-optimization-validation/cli.js +1 -1
  11. package/ci/test-optimization-validation/command-runner.js +2 -3
  12. package/ci/test-optimization-validation/executable.js +1 -1
  13. package/ci/test-optimization-validation/framework-adapters/cucumber.js +1 -1
  14. package/ci/test-optimization-validation/literal-environment.js +2 -2
  15. package/ci/test-optimization-validation/manifest-scaffold.js +1 -1
  16. package/ci/test-optimization-validation/offline-fixtures.js +1 -1
  17. package/ci/test-optimization-validation/redaction.js +3 -3
  18. package/ci/test-optimization-validation/runner-contract.js +10 -10
  19. package/ci/test-optimization-validation/scenarios/ci-wiring.js +1 -1
  20. package/ci/vitest-no-worker-init-annotations.mjs +4 -0
  21. package/ci/vitest-no-worker-init-node-setup.mjs +22 -0
  22. package/ci/vitest-no-worker-init-runner-setup.mjs +7 -5
  23. package/ci/vitest-no-worker-init-setup.mjs +34 -12
  24. package/ci/vitest-no-worker-init-v5-setup.mjs +6 -0
  25. package/ext/exporters.js +1 -0
  26. package/index.d.ts +35 -5
  27. package/loader-hook.mjs +53 -0
  28. package/openfeature/exposure-hook.d.ts +66 -0
  29. package/openfeature/exposure-hook.js +5 -0
  30. package/package.json +23 -20
  31. package/packages/datadog-core/src/storage.js +1 -1
  32. package/packages/datadog-esbuild/index.js +70 -7
  33. package/packages/datadog-instrumentations/index.js +2 -1
  34. package/packages/datadog-instrumentations/src/cucumber.js +64 -21
  35. package/packages/datadog-instrumentations/src/cypress-config.js +163 -15
  36. package/packages/datadog-instrumentations/src/graphql.js +9 -3
  37. package/packages/datadog-instrumentations/src/grpc/server.js +23 -6
  38. package/packages/datadog-instrumentations/src/helpers/bundler-register.js +27 -8
  39. package/packages/datadog-instrumentations/src/helpers/fetch.js +5 -1
  40. package/packages/datadog-instrumentations/src/helpers/graphql-jit-runtime.js +30 -8
  41. package/packages/datadog-instrumentations/src/helpers/hooks.js +2 -1
  42. package/packages/datadog-instrumentations/src/helpers/register.js +9 -0
  43. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +16 -6
  44. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +10 -0
  45. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql-jit.js +3 -1
  46. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/jest.js +12 -0
  47. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/react-router.js +49 -0
  48. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/typesafe.js +23 -0
  49. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/vitest.js +8 -0
  50. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/webdriverio.js +12 -0
  51. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +8 -0
  52. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.js +19 -2
  53. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +13 -0
  54. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +1 -1
  55. package/packages/datadog-instrumentations/src/jest.js +332 -137
  56. package/packages/datadog-instrumentations/src/mariadb-bundle.js +69 -11
  57. package/packages/datadog-instrumentations/src/mariadb.js +13 -6
  58. package/packages/datadog-instrumentations/src/mocha/common.js +89 -8
  59. package/packages/datadog-instrumentations/src/mocha/main.js +11 -2
  60. package/packages/datadog-instrumentations/src/mocha/utils.js +92 -13
  61. package/packages/datadog-instrumentations/src/mocha/worker.js +1 -1
  62. package/packages/datadog-instrumentations/src/nova-sonic/session.js +25 -16
  63. package/packages/datadog-instrumentations/src/oracledb.js +33 -0
  64. package/packages/datadog-instrumentations/src/pg.js +2 -1
  65. package/packages/datadog-instrumentations/src/playwright.js +81 -26
  66. package/packages/datadog-instrumentations/src/react-router.js +106 -0
  67. package/packages/datadog-instrumentations/src/stripe.js +23 -12
  68. package/packages/datadog-instrumentations/src/typesafe.js +89 -0
  69. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +84 -47
  70. package/packages/datadog-instrumentations/src/vitest-main.js +33 -3
  71. package/packages/datadog-instrumentations/src/vitest-test-annotations.js +20 -0
  72. package/packages/datadog-instrumentations/src/vitest-util.js +5 -2
  73. package/packages/datadog-instrumentations/src/vitest-worker.js +39 -17
  74. package/packages/datadog-instrumentations/src/vitest.js +16 -6
  75. package/packages/datadog-plugin-cucumber/src/index.js +5 -0
  76. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +277 -44
  77. package/packages/datadog-plugin-cypress/src/index.js +1 -1
  78. package/packages/datadog-plugin-cypress/src/lifecycle-owner.js +20 -0
  79. package/packages/datadog-plugin-cypress/src/plugin.js +10 -0
  80. package/packages/datadog-plugin-cypress/src/retry-config-observer.js +281 -0
  81. package/packages/datadog-plugin-cypress/src/setup-handoff.js +125 -0
  82. package/packages/datadog-plugin-cypress/src/support.js +1217 -437
  83. package/packages/datadog-plugin-graphql/src/execute.js +2 -2
  84. package/packages/datadog-plugin-graphql/src/utils.js +5 -5
  85. package/packages/datadog-plugin-jest/src/index.js +25 -3
  86. package/packages/datadog-plugin-mocha/src/index.js +47 -6
  87. package/packages/datadog-plugin-oracledb/src/connection-parser.js +21 -11
  88. package/packages/datadog-plugin-playwright/src/index.js +4 -0
  89. package/packages/datadog-plugin-react-router/src/index.js +118 -0
  90. package/packages/datadog-plugin-typesafe/src/index.js +17 -0
  91. package/packages/datadog-plugin-typesafe/src/tracing.js +31 -0
  92. package/packages/datadog-plugin-vitest/src/index.js +8 -0
  93. package/packages/dd-trace/src/agent/info.js +2 -1
  94. package/packages/dd-trace/src/aiguard/evaluation.js +143 -1
  95. package/packages/dd-trace/src/aiguard/sdk.js +0 -11
  96. package/packages/dd-trace/src/appsec/iast/path-line.js +2 -1
  97. package/packages/dd-trace/src/appsec/stack_trace.js +3 -2
  98. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/worker/index.js +3 -2
  99. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +9 -16
  100. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +4 -2
  101. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +9 -16
  102. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +9 -14
  103. package/packages/dd-trace/src/ci-visibility/requests/route.js +44 -0
  104. package/packages/dd-trace/src/ci-visibility/telemetry-logs.js +5 -0
  105. package/packages/dd-trace/src/ci-visibility/test-annotations.js +72 -0
  106. package/packages/dd-trace/src/ci-visibility/test-declaration-annotations.js +170 -0
  107. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +9 -16
  108. package/packages/dd-trace/src/config/defaults.js +4 -3
  109. package/packages/dd-trace/src/config/generated-config-types.d.ts +6 -0
  110. package/packages/dd-trace/src/config/index.js +140 -39
  111. package/packages/dd-trace/src/config/parsers.js +9 -1
  112. package/packages/dd-trace/src/config/supported-configurations.json +25 -0
  113. package/packages/dd-trace/src/debugger/devtools_client/breakpoints.js +6 -5
  114. package/packages/dd-trace/src/debugger/devtools_client/condition.js +5 -5
  115. package/packages/dd-trace/src/debugger/devtools_client/snapshot/collector.js +4 -6
  116. package/packages/dd-trace/src/debugger/probe_sampler.js +6 -6
  117. package/packages/dd-trace/src/debugger/unsupported-runtime.js +16 -0
  118. package/packages/dd-trace/src/encode/0.4.js +2 -2
  119. package/packages/dd-trace/src/esm-module-load.js +58 -0
  120. package/packages/dd-trace/src/exporter.js +25 -6
  121. package/packages/dd-trace/src/exporters/agent/index.js +3 -1
  122. package/packages/dd-trace/src/exporters/agentless/index.js +3 -1
  123. package/packages/dd-trace/src/exporters/common/request.js +4 -4
  124. package/packages/dd-trace/src/exporters/llmobs/index.js +135 -0
  125. package/packages/dd-trace/src/exporters/log/index.js +4 -3
  126. package/packages/dd-trace/src/llmobs/agent-manifest.js +19 -2
  127. package/packages/dd-trace/src/llmobs/constants/tags.js +4 -0
  128. package/packages/dd-trace/src/llmobs/experiments/index.js +2 -3
  129. package/packages/dd-trace/src/llmobs/experiments/noop.js +5 -2
  130. package/packages/dd-trace/src/llmobs/index.js +13 -2
  131. package/packages/dd-trace/src/llmobs/plugins/claude-agent-sdk/index.js +1 -1
  132. package/packages/dd-trace/src/llmobs/plugins/genai/index.js +1 -1
  133. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +8 -4
  134. package/packages/dd-trace/src/llmobs/plugins/openai/constants.js +5 -0
  135. package/packages/dd-trace/src/llmobs/plugins/openai/index.js +9 -1
  136. package/packages/dd-trace/src/llmobs/plugins/typesafe/index.js +102 -0
  137. package/packages/dd-trace/src/llmobs/prompts/cache.js +3 -1
  138. package/packages/dd-trace/src/llmobs/sdk.js +17 -5
  139. package/packages/dd-trace/src/llmobs/span_processor.js +222 -12
  140. package/packages/dd-trace/src/llmobs/tagger.js +21 -8
  141. package/packages/dd-trace/src/llmobs/util.js +10 -4
  142. package/packages/dd-trace/src/llmobs/writers/util.js +3 -3
  143. package/packages/dd-trace/src/log/writer.js +7 -1
  144. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +64 -6
  145. package/packages/dd-trace/src/openfeature/configuration_source.js +18 -2
  146. package/packages/dd-trace/src/openfeature/debug-logging-hook.js +66 -3
  147. package/packages/dd-trace/src/openfeature/exposure-hook.js +185 -0
  148. package/packages/dd-trace/src/openfeature/flagging_provider.js +39 -13
  149. package/packages/dd-trace/src/openfeature/index.js +6 -0
  150. package/packages/dd-trace/src/openfeature/remote_config.js +16 -3
  151. package/packages/dd-trace/src/openfeature/writers/base.js +62 -27
  152. package/packages/dd-trace/src/openfeature/writers/exposures.js +161 -1
  153. package/packages/dd-trace/src/openfeature/writers/flag-eval-evp-hook.js +5 -0
  154. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-aggregation.js +9 -4
  155. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-payload.js +2 -0
  156. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-pii.js +2 -0
  157. package/packages/dd-trace/src/openfeature/writers/split-features.js +25 -0
  158. package/packages/dd-trace/src/openfeature/writers/util.js +4 -4
  159. package/packages/dd-trace/src/opentelemetry/metrics/periodic_metric_reader.js +2 -2
  160. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +18 -1
  161. package/packages/dd-trace/src/opentelemetry/tracer_provider.js +5 -1
  162. package/packages/dd-trace/src/opentracing/tracer.js +9 -13
  163. package/packages/dd-trace/src/otel-thread-ctx.js +47 -21
  164. package/packages/dd-trace/src/plugin_manager.js +1 -2
  165. package/packages/dd-trace/src/plugins/ci_plugin.js +4 -4
  166. package/packages/dd-trace/src/plugins/index.js +3 -0
  167. package/packages/dd-trace/src/plugins/tracing.js +1 -2
  168. package/packages/dd-trace/src/plugins/util/git.js +102 -40
  169. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +2 -4
  170. package/packages/dd-trace/src/plugins/util/stacktrace.js +2 -1
  171. package/packages/dd-trace/src/plugins/util/test.js +28 -6
  172. package/packages/dd-trace/src/plugins/util/web.js +106 -20
  173. package/packages/dd-trace/src/process-tags/index.js +1 -1
  174. package/packages/dd-trace/src/profiling/config.js +6 -3
  175. package/packages/dd-trace/src/proxy.js +15 -4
  176. package/packages/dd-trace/src/serverless.js +3 -2
  177. package/packages/dd-trace/src/span_processor.js +21 -9
  178. package/packages/dd-trace/src/span_stats.js +32 -3
  179. package/packages/dd-trace/src/startup-log.js +2 -1
  180. package/packages/dd-trace/src/tagger.js +7 -5
  181. package/packages/dd-trace/src/telemetry/dependencies.js +4 -0
  182. package/packages/dd-trace/src/telemetry/index.js +3 -0
  183. package/packages/dd-trace/src/telemetry/logs/index.js +21 -2
  184. package/packages/dd-trace/src/telemetry/logs/log-collector.js +2 -1
  185. package/packages/dd-trace/src/telemetry/telemetry.js +10 -3
  186. package/packages/dd-trace/src/util.js +9 -5
  187. package/register.js +2 -1
  188. package/vendor/dist/@apm-js-collab/code-transformer/index.js +8 -8
  189. package/vendor/dist/@datadog/openfeature-node-server/index.js +1 -1
  190. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.d.ts +78 -0
  191. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.js +1 -1
  192. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  193. package/vendor/dist/@opentelemetry/resources/LICENSE +0 -201
  194. package/vendor/dist/@opentelemetry/resources/index.js +0 -1
@@ -129,6 +129,7 @@ let earlyFlakeDetectionRetryPolicy = EMPTY_EFD_RETRY_POLICY
129
129
  let earlyFlakeDetectionFaultyThreshold = 0
130
130
  let isEarlyFlakeDetectionFaulty = false
131
131
  let isFlakyTestRetriesEnabled = false
132
+ let hasAutomaticRetries = false
132
133
  let isDynamicAtrEnabled = false
133
134
  let dynamicAtrBuckets
134
135
  let isKnownTestsEnabled = false
@@ -138,6 +139,7 @@ let testManagementAttemptToFixRetries = 0
138
139
  let testManagementTests = {}
139
140
  let modifiedFiles = {}
140
141
  let numTestRetries = 0
142
+ let frameworkRetryCount = 0
141
143
  let knownTests = {}
142
144
  let skippedSuites = []
143
145
  let isSuitesSkipped = false
@@ -255,7 +257,9 @@ function configureParallelWorkerWorldParameters (options) {
255
257
  }
256
258
 
257
259
  options.worldParameters._ddIsFlakyTestRetriesEnabled = isFlakyTestRetriesEnabled
260
+ options.worldParameters._ddHasAutomaticRetries = hasAutomaticRetries
258
261
  options.worldParameters._ddNumTestRetries = numTestRetries
262
+ options.worldParameters._ddFrameworkRetryCount = frameworkRetryCount
259
263
  options.worldParameters._ddIsDynamicAtrEnabled = isDynamicAtrEnabled
260
264
  options.worldParameters._ddDynamicAtrBuckets = dynamicAtrBuckets
261
265
 
@@ -298,6 +302,7 @@ function readParallelWorkerWorldParameters (options) {
298
302
  /**
299
303
  * @param {object} worldParameters
300
304
  * @param {boolean} [worldParameters._ddIsFlakyTestRetriesEnabled]
305
+ * @param {boolean} [worldParameters._ddHasAutomaticRetries]
301
306
  * @param {number} [worldParameters._ddNumTestRetries]
302
307
  * @param {boolean} [worldParameters._ddIsDynamicAtrEnabled]
303
308
  * @param {number[]} [worldParameters._ddDynamicAtrBuckets]
@@ -305,7 +310,9 @@ function readParallelWorkerWorldParameters (options) {
305
310
  * [worldParameters._ddEarlyFlakeDetectionRetryPolicy]
306
311
  */
307
312
  function readParallelWorkerAtrParameters (worldParameters) {
313
+ frameworkRetryCount = worldParameters._ddFrameworkRetryCount || 0
308
314
  isFlakyTestRetriesEnabled = !!worldParameters._ddIsFlakyTestRetriesEnabled
315
+ hasAutomaticRetries = !!worldParameters._ddHasAutomaticRetries
309
316
  numTestRetries = worldParameters._ddNumTestRetries ?? 0
310
317
  isDynamicAtrEnabled = !!worldParameters._ddIsDynamicAtrEnabled
311
318
  dynamicAtrBuckets = worldParameters._ddDynamicAtrBuckets
@@ -388,9 +395,10 @@ function handleParallelTestCaseFinished (pickle, worstTestStepResult, usesNumeri
388
395
  const finished = (pickleResultByFile[testFileAbsolutePath] ||= [])
389
396
 
390
397
  const isAttemptToFix = isTestManagementTestsEnabled &&
391
- getTestProperties(getTestSuitePath(testFileAbsolutePath, process.cwd()), pickle.name).attemptToFix
398
+ getTestProperties(getTestSuitePath(testFileAbsolutePath, process.cwd()), pickle.name, pickle).attemptToFix
392
399
 
393
- if (!isAttemptToFix && shouldRunEarlyFlakeDetection() && (isNew || modifiedTestsByPickleId.get(pickle.id))) {
400
+ if (!getScenarioAnnotations(pickle).noAutoRetry && !isAttemptToFix && shouldRunEarlyFlakeDetection() &&
401
+ (isNew || modifiedTestsByPickleId.get(pickle.id))) {
394
402
  let testStatuses = efdStatusesByPickleId.get(pickle.id)
395
403
  if (testStatuses) {
396
404
  testStatuses.push(status)
@@ -573,11 +581,25 @@ function isNewTest (testSuite, testName) {
573
581
  return !testsForSuite.includes(testName)
574
582
  }
575
583
 
576
- function getTestProperties (testSuite, testName) {
584
+ /** @param {{ tags?: Array<{ name: string }> }} pickle */
585
+ function getScenarioAnnotations (pickle) {
586
+ const tags = pickle.tags || []
587
+ return {
588
+ mustFail: tags.some(tag => tag.name === '@datadog:prevent_failure_suppression'),
589
+ noAutoRetry: tags.some(tag => tag.name === '@datadog:no_auto_retry'),
590
+ }
591
+ }
592
+
593
+ function getTestProperties (testSuite, testName, pickle) {
577
594
  const { attempt_to_fix: attemptToFix, disabled, quarantined } =
578
595
  testManagementTests?.cucumber?.suites?.[testSuite]?.tests?.[testName]?.properties || {}
579
596
 
580
- return { attemptToFix, disabled, quarantined }
597
+ const { mustFail, noAutoRetry } = getScenarioAnnotations(pickle)
598
+ return {
599
+ attemptToFix: attemptToFix && !noAutoRetry,
600
+ disabled: disabled && !mustFail,
601
+ quarantined: quarantined && !mustFail,
602
+ }
581
603
  }
582
604
 
583
605
  function getTestStatusFromRetries (testStatuses) {
@@ -741,9 +763,11 @@ function publishRetriedAttempt (runner, state) {
741
763
  const nextAttempt = currentAttempt + 1
742
764
  const failedAttemptCtx = numAttemptToCtx.get(currentAttempt)
743
765
  const isFirstAttempt = currentAttempt === 0
744
- const isAtrRetry = !isFirstAttempt && isFlakyTestRetriesEnabled
766
+ const noAutoRetry = getScenarioAnnotations(runner.pickle).noAutoRetry
767
+ const isAtrRetry = !isFirstAttempt && state.hasAutomaticRetries && !noAutoRetry
745
768
 
746
- if (isFirstAttempt && isDynamicAtrEnabled && isFlakyTestRetriesEnabled) {
769
+ if (!noAutoRetry && isFirstAttempt && isDynamicAtrEnabled && isFlakyTestRetriesEnabled) {
770
+ state.hasAutomaticRetries = true
747
771
  state.dynamicAtrRetryCount = getDynamicAtrRetryCount(
748
772
  performance.now() - state.executionStart,
749
773
  earlyFlakeDetectionRetryPolicy,
@@ -755,7 +779,7 @@ function publishRetriedAttempt (runner, state) {
755
779
  }
756
780
 
757
781
  // ATR: record this attempt as failed so when run().finally runs (after retry) we have all statuses
758
- if (isFlakyTestRetriesEnabled) {
782
+ if (state.hasAutomaticRetries && !noAutoRetry) {
759
783
  const nameForKey = getCucumberTestName(runner.pickle.name, currentAttempt > 0)
760
784
  const atrKey = `${runner.pickle.uri}:${nameForKey}`
761
785
  if (atrStatusesByScenarioKey.has(atrKey)) {
@@ -809,10 +833,11 @@ function wrapRun (pl, isLatestVersion, version) {
809
833
  return run.apply(this, args)
810
834
  }
811
835
 
812
- // Cucumber 8–10 workers construct runners directly, without the newer
836
+ // Cucumber 7–10 workers construct runners directly, without the newer
813
837
  // runTestCase wrapper that reads the coordinator's configuration.
814
- if (getEnvironmentVariable('CUCUMBER_WORKER_ID') && satisfies(version, '>=8.0.0 <11.0.0')) {
815
- readParallelWorkerAtrParameters(this.worldParameters)
838
+ if (getEnvironmentVariable('CUCUMBER_WORKER_ID') && satisfies(version, '>=7.0.0 <11.0.0')) {
839
+ frameworkRetryCount = this.worldParameters._ddFrameworkRetryCount || 0
840
+ if (satisfies(version, '>=8.0.0')) readParallelWorkerAtrParameters(this.worldParameters)
816
841
  }
817
842
 
818
843
  const testFileAbsolutePath = this.pickle.uri
@@ -820,7 +845,14 @@ function wrapRun (pl, isLatestVersion, version) {
820
845
 
821
846
  const testSourceLine = this.gherkinDocument?.feature?.location?.line
822
847
 
848
+ const testAnnotations = getScenarioAnnotations(this.pickle)
849
+ // Explicit native retries already include the pickle's retry-tag-filter decision.
850
+ if (testAnnotations.noAutoRetry && frameworkRetryCount === 0) this.maxAttempts = 1
823
851
  const testStartPayload = {
852
+ testAnnotations,
853
+ assignedProperties: isTestManagementTestsEnabled
854
+ ? testManagementTests?.cucumber?.suites?.[testSuitePath]?.tests?.[this.pickle.name]?.properties
855
+ : undefined,
824
856
  testName: this.pickle.name,
825
857
  testFileAbsolutePath,
826
858
  testSourceLine,
@@ -831,10 +863,10 @@ function wrapRun (pl, isLatestVersion, version) {
831
863
  }
832
864
  const ctx = testStartPayload
833
865
  const promises = {}
834
- const state = { numAttempt: 0, promises, testStartPayload }
866
+ const state = { numAttempt: 0, promises, testStartPayload, hasAutomaticRetries }
835
867
  numAttemptToCtx.set(state.numAttempt, ctx)
836
868
  runnerToRetryState.set(this, state)
837
- if (isTestManagementTestsEnabled && getTestProperties(testSuitePath, this.pickle.name).attemptToFix) {
869
+ if (isTestManagementTestsEnabled && getTestProperties(testSuitePath, this.pickle.name, this.pickle).attemptToFix) {
838
870
  logAttemptToFixTestExecution(testSuitePath, this.pickle.name, loggedAttemptToFixTests)
839
871
  }
840
872
  testStartCh.runStores(ctx, () => {})
@@ -889,7 +921,7 @@ function wrapRun (pl, isLatestVersion, version) {
889
921
 
890
922
  if (isTestManagementTestsEnabled) {
891
923
  const testSuitePath = getTestSuitePath(testFileAbsolutePath, process.cwd())
892
- const testProperties = getTestProperties(testSuitePath, testName)
924
+ const testProperties = getTestProperties(testSuitePath, testName, this.pickle)
893
925
  const numRetries = numRetriesByPickleId.get(this.pickle.id)
894
926
  isAttemptToFix = testProperties.attemptToFix
895
927
  isAttemptToFixRetry = isAttemptToFix && numRetries > 0
@@ -925,7 +957,7 @@ function wrapRun (pl, isLatestVersion, version) {
925
957
  }
926
958
 
927
959
  if (
928
- shouldRunEarlyFlakeDetection() &&
960
+ !testAnnotations.noAutoRetry && shouldRunEarlyFlakeDetection() &&
929
961
  !isAttemptToFix &&
930
962
  status !== 'skip' &&
931
963
  (isNew || isModified) &&
@@ -961,7 +993,8 @@ function wrapRun (pl, isLatestVersion, version) {
961
993
 
962
994
  // ATR: accumulate statuses by stable scenario key (uri:name) so retries are grouped.
963
995
  // Cucumber appends " (attempt N)" or " (attempt N, retried)" to the scenario name; normalize for keying.
964
- if (isFlakyTestRetriesEnabled && !isAttemptToFix && !isEfdRetry && numTestRetries > 0) {
996
+ if (!testAnnotations.noAutoRetry && state.hasAutomaticRetries &&
997
+ !isAttemptToFix && !isEfdRetry && numTestRetries > 0) {
965
998
  const atrKey = `${this.pickle.uri}:${testName}`
966
999
  if (atrStatusesByScenarioKey.has(atrKey)) {
967
1000
  atrStatusesByScenarioKey.get(atrKey).push(status)
@@ -1010,7 +1043,9 @@ function wrapRun (pl, isLatestVersion, version) {
1010
1043
 
1011
1044
  // Notice that ATR is handled using cucumber native retries features.
1012
1045
  // Therefore, if we reach this point, we are certain that it's the last ATR execution
1013
- const isLastAtrRetry = isFlakyTestRetriesEnabled && !isAttemptToFix && !isEfdRetry &&
1046
+ const isLastAtrRetry = satisfies(version, '>=8.0.0') &&
1047
+ !testAnnotations.noAutoRetry && state.hasAutomaticRetries &&
1048
+ !isAttemptToFix && !isEfdRetry &&
1014
1049
  numTestRetries > 0 && this.maxAttempts > 1
1015
1050
 
1016
1051
  const statuses = lastStatusByPickleId.get(this.pickle.id)
@@ -1039,8 +1074,8 @@ function wrapRun (pl, isLatestVersion, version) {
1039
1074
  error,
1040
1075
  isNew,
1041
1076
  isEfdRetry,
1042
- isFlakyRetry: state.numAttempt > 0 && isFlakyTestRetriesEnabled,
1043
- isExternalRetry: state.numAttempt > 0 && !isFlakyTestRetriesEnabled,
1077
+ isFlakyRetry: state.numAttempt > 0 && state.hasAutomaticRetries && !testAnnotations.noAutoRetry,
1078
+ isExternalRetry: state.numAttempt > 0 && (!state.hasAutomaticRetries || testAnnotations.noAutoRetry),
1044
1079
  isAttemptToFix,
1045
1080
  isAttemptToFixRetry,
1046
1081
  hasFailedAllRetries,
@@ -1261,7 +1296,10 @@ function getWrappedStart (start, frameworkVersion, isParallel = false, isCoordin
1261
1296
  const processArgv = process.argv.slice(2).join(' ')
1262
1297
  const command = getEnvironmentVariable('npm_lifecycle_script') || `cucumber-js ${processArgv}`
1263
1298
 
1264
- if (isFlakyTestRetriesEnabled && !options.retry && numTestRetries > 0) {
1299
+ const originalRetryCount = options.retry
1300
+ frameworkRetryCount = options.retry || 0
1301
+ hasAutomaticRetries = isFlakyTestRetriesEnabled && !options.retry && numTestRetries > 0
1302
+ if (hasAutomaticRetries) {
1265
1303
  options.retry = numTestRetries
1266
1304
  }
1267
1305
 
@@ -1303,6 +1341,8 @@ function getWrappedStart (start, frameworkVersion, isParallel = false, isCoordin
1303
1341
  log.error('Cucumber test session finalization error: %s', finalizationError)
1304
1342
  }
1305
1343
  throw error
1344
+ } finally {
1345
+ if (hasAutomaticRetries) options.retry = originalRetryCount
1306
1346
  }
1307
1347
  const success = satisfies(frameworkVersion, '>=13.1.0') ? result.success : result
1308
1348
 
@@ -1414,9 +1454,10 @@ function getWrappedRunTestCase (runTestCaseFunction, isNewerCucumberVersion = fa
1414
1454
  let isQuarantined = false
1415
1455
  let isModified = false
1416
1456
 
1457
+ const testAnnotations = getScenarioAnnotations(pickle)
1417
1458
  const originalDryRun = this.options.dryRun
1418
1459
  if (isTestManagementTestsEnabled) {
1419
- const testProperties = getTestProperties(testSuitePath, pickle.name)
1460
+ const testProperties = getTestProperties(testSuitePath, pickle.name, pickle)
1420
1461
  isAttemptToFix = testProperties.attemptToFix
1421
1462
  isDisabled = testProperties.disabled
1422
1463
  isQuarantined = testProperties.quarantined
@@ -1488,8 +1529,10 @@ function getWrappedRunTestCase (runTestCaseFunction, isNewerCucumberVersion = fa
1488
1529
  }
1489
1530
  }
1490
1531
  const originalRetry = this.options.retry
1491
- const isEfdTest = !isAttemptToFix && shouldRunEarlyFlakeDetection() && (isNew || isModified)
1532
+ const isEfdTest = !testAnnotations.noAutoRetry && !isAttemptToFix &&
1533
+ shouldRunEarlyFlakeDetection() && (isNew || isModified)
1492
1534
  const isManagedRetry = isAttemptToFix || isEfdTest
1535
+ if (testAnnotations.noAutoRetry) this.options.retry = frameworkRetryCount
1493
1536
  if (isManagedRetry) {
1494
1537
  this.options.retry = 0
1495
1538
  }
@@ -15,6 +15,7 @@ const {
15
15
  const { channel } = require('./helpers/instrument')
16
16
 
17
17
  const DD_CONFIG_WRAPPED = Symbol.for('dd-trace.cypress.config.wrapped')
18
+ const DD_SUPPORT_OWNER = Symbol.for('dd-trace.cypress.support-owner')
18
19
  const DD_CYPRESS_AFTER_SPEC_HANDLER = Symbol.for('dd-trace.cypress.after-spec.handler')
19
20
  const DD_CYPRESS_AFTER_RUN_HANDLER = Symbol.for('dd-trace.cypress.after-run.handler')
20
21
  const DD_CYPRESS_TASK_HANDLER = Symbol.for('dd-trace.cypress.task.handler')
@@ -25,6 +26,7 @@ const CONFIG_INSTRUMENTATION_NOT_INSTALLED =
25
26
  'Cypress configurations that cannot be intercepted through cypress.defineConfig were not auto-instrumented.'
26
27
  const generatedFilesForExitCleanup = new Set()
27
28
  let exitCleanupRegistered = false
29
+ let stopManualSupportSetup
28
30
 
29
31
  const setupNodeEventsCh = channel('ci:cypress:setup-node-events')
30
32
 
@@ -39,6 +41,7 @@ if (loadCh.hasSubscribers) {
39
41
 
40
42
  const noopTask = {
41
43
  'dd:testSuiteStart': () => null,
44
+ 'dd:testDeclarations': () => null,
42
45
  'dd:beforeEach': () => ({}),
43
46
  'dd:afterEach': () => null,
44
47
  'dd:addTags': () => null,
@@ -250,13 +253,20 @@ function mergeReturnedConfig (config, updatedConfig) {
250
253
  }
251
254
 
252
255
  const mergedConfig = { ...config }
253
-
254
- for (const [key, value] of Object.entries(updatedConfig)) {
255
- mergedConfig[key] = isPlainObject(value) && isPlainObject(mergedConfig[key])
256
- ? mergeReturnedConfig(mergedConfig[key], value)
257
- : value
256
+ // Retain the values already read for the reply, rather than invoking user getters again at IPC.
257
+ const returnedConfig = Object.fromEntries(Object.entries(updatedConfig))
258
+
259
+ for (const [key, value] of Object.entries(returnedConfig)) {
260
+ if (isPlainObject(value) && isPlainObject(mergedConfig[key]) && value !== mergedConfig[key]) {
261
+ mergedConfig[key] = mergeReturnedConfig(mergedConfig[key], value)
262
+ // Keep only the returned overrides, using values already read by the recursive merge.
263
+ returnedConfig[key] = mergedConfig[key][Symbol.for('dd-trace.cypress.returned-config')]
264
+ } else {
265
+ mergedConfig[key] = value
266
+ }
258
267
  }
259
268
 
269
+ Object.defineProperty(mergedConfig, Symbol.for('dd-trace.cypress.returned-config'), { value: returnedConfig })
260
270
  return mergedConfig
261
271
  }
262
272
 
@@ -289,9 +299,13 @@ function getRelativeImportPath (fromDirectory, importedFile) {
289
299
  * @param {string} directory writable directory inside the Cypress project
290
300
  * @param {string|false|undefined} originalSupportFile user's support file
291
301
  * @param {string} browserHooksSource Datadog browser-side support hooks
302
+ * @param {boolean} deferLifecycle whether manual support owns lifecycle registration
303
+ * @param {string} lifecycleOwnerSource browser lifecycle ownership detection
292
304
  * @returns {string[]} generated files
293
305
  */
294
- function createSupportWrapper (directory, originalSupportFile, browserHooksSource) {
306
+ function createSupportWrapper (
307
+ directory, originalSupportFile, browserHooksSource, deferLifecycle, lifecycleOwnerSource
308
+ ) {
295
309
  const suffix = `${process.pid}-${randomUUID()}`
296
310
  const browserHooksFile = path.join(directory, `dd-cypress-support-hooks-${suffix}.mjs`)
297
311
  const wrapperFile = path.join(directory, `dd-cypress-support-${suffix}.mjs`)
@@ -305,9 +319,47 @@ function createSupportWrapper (directory, originalSupportFile, browserHooksSourc
305
319
 
306
320
  const generatedFiles = []
307
321
  try {
308
- writeExclusiveFile(browserHooksFile, browserHooksSource)
322
+ const guardedSource = `const ddSupportRoot = Cypress.mocha.getRootSuite()
323
+ const ddSupportKey = Symbol.for('dd-trace.cypress.support-installed')
324
+ const ddHasLifecycle = (() => {
325
+ const module = { exports: {} }
326
+ ${lifecycleOwnerSource}
327
+ return module.exports
328
+ })()
329
+ ddSupportRoot[Symbol.for('dd-trace.cypress.has-lifecycle')] = ddHasLifecycle
330
+ if (!ddSupportRoot[ddSupportKey] && !ddHasLifecycle(ddSupportRoot)) {
331
+ const positions = {}
332
+ for (const key of ['_beforeAll', '_beforeEach', '_afterAll', '_afterEach']) {
333
+ positions[key] = Array.isArray(ddSupportRoot[key]) ? ddSupportRoot[key].length : 0
334
+ }
335
+ ddSupportRoot[Symbol.for('dd-trace.cypress.lifecycle-positions')] = positions
336
+ ddSupportRoot[Symbol.for('dd-trace.cypress.defer-lifecycle')] = ${deferLifecycle}
337
+ ${browserHooksSource}
338
+ ddSupportRoot[ddSupportKey] = true
339
+ }
340
+ `
341
+ writeExclusiveFile(browserHooksFile, guardedSource)
309
342
  generatedFiles.push(browserHooksFile)
310
- writeExclusiveFile(wrapperFile, `${wrapperImports.join('\n')}\n`)
343
+ const finalize = `const root = Cypress.mocha.getRootSuite()
344
+ const install = root[Symbol.for('dd-trace.cypress.install-lifecycle')]
345
+ const hasLifecycle = root[Symbol.for('dd-trace.cypress.has-lifecycle')]
346
+ if (typeof install === 'function' && (!hasLifecycle || !hasLifecycle(root))) {
347
+ const phases = ['_beforeAll', '_beforeEach', '_afterAll', '_afterEach']
348
+ const lengths = {}
349
+ for (const key of phases) lengths[key] = Array.isArray(root[key]) ? root[key].length : 0
350
+ install()
351
+ // A Node-only manual plugin needs automatic browser hooks before user hooks.
352
+ // Move only the hooks just installed; an actual manual owner never enters here.
353
+ const positions = root[Symbol.for('dd-trace.cypress.lifecycle-positions')]
354
+ for (const key of phases) {
355
+ if (positions && Array.isArray(root[key])) {
356
+ const added = root[key].splice(lengths[key])
357
+ root[key].splice(positions[key], 0, ...added)
358
+ }
359
+ }
360
+ }
361
+ `
362
+ writeExclusiveFile(wrapperFile, `${wrapperImports.join('\n')}\n${finalize}`)
311
363
  generatedFiles.push(wrapperFile)
312
364
  } catch (error) {
313
365
  for (const generatedFile of generatedFiles) removeGeneratedFile(generatedFile)
@@ -323,21 +375,26 @@ function createSupportWrapper (directory, originalSupportFile, browserHooksSourc
323
375
  * generated paths for cleanup, or undefined if injection was skipped.
324
376
  *
325
377
  * @param {object} config Cypress resolved config object
378
+ * @param {boolean} [manualLifecycle] whether the manual entry point owns lifecycle registration
326
379
  * @returns {string[]|undefined} generated file paths, or undefined if skipped
327
380
  */
328
- function injectSupportFile (config) {
381
+ function injectSupportFile (config, manualLifecycle = false) {
329
382
  const originalSupportFile = config.supportFile
330
383
 
384
+ const supportOwner = config[DD_SUPPORT_OWNER]
385
+ if (generatedFilesForExitCleanup.has(originalSupportFile) &&
386
+ (!manualLifecycle || (supportOwner?.path === originalSupportFile && supportOwner.deferLifecycle))) return
387
+ let deferLifecycle = manualLifecycle ||
388
+ (supportOwner && supportOwner.path === originalSupportFile && supportOwner.deferLifecycle)
389
+
331
390
  if (originalSupportFile) {
332
391
  try {
333
392
  const content = fs.readFileSync(originalSupportFile, 'utf8')
334
- // Naive check: skip lines starting with // or * to avoid matching commented-out imports.
335
- const hasActiveDdTraceImport = content.split('\n').some(line => {
393
+ deferLifecycle ||= content.split('\n').some(line => {
336
394
  const trimmed = line.trim()
337
395
  return trimmed.includes('dd-trace/ci/cypress/support') &&
338
396
  !trimmed.startsWith('//') && !trimmed.startsWith('*')
339
397
  })
340
- if (hasActiveDdTraceImport) return
341
398
  } catch (error) {
342
399
  logBrowserInstrumentationError(
343
400
  'Datadog could not read the Cypress support file %s: %s. %s',
@@ -351,9 +408,11 @@ function injectSupportFile (config) {
351
408
 
352
409
  let browserHooksSource
353
410
  let browserHooksPath
411
+ let lifecycleOwnerSource
354
412
  try {
355
413
  browserHooksPath = require.resolve('../../datadog-plugin-cypress/src/support')
356
414
  browserHooksSource = fs.readFileSync(browserHooksPath, 'utf8')
415
+ lifecycleOwnerSource = fs.readFileSync(require.resolve('../../datadog-plugin-cypress/src/lifecycle-owner'), 'utf8')
357
416
  } catch (error) {
358
417
  logBrowserInstrumentationError(
359
418
  'Datadog could not read its Cypress browser support hooks: %s. %s',
@@ -372,8 +431,12 @@ function injectSupportFile (config) {
372
431
  for (const directory of new Set(candidateDirectories)) {
373
432
  if (projectRoot && !isPathInside(projectRoot, directory)) continue
374
433
  try {
375
- const generatedFiles = createSupportWrapper(directory, originalSupportFile, browserHooksSource)
434
+ const generatedFiles = createSupportWrapper(
435
+ directory, originalSupportFile, browserHooksSource, !!deferLifecycle, lifecycleOwnerSource
436
+ )
376
437
  config.supportFile = generatedFiles[1]
438
+ // Shared across SDK copies, but scoped to this exact generated support path.
439
+ config[DD_SUPPORT_OWNER] = { path: config.supportFile, deferLifecycle: !!deferLifecycle }
377
440
  return generatedFiles
378
441
  } catch (error) {
379
442
  failures.push({ directory, error })
@@ -396,6 +459,90 @@ function injectSupportFile (config) {
396
459
  }
397
460
  }
398
461
 
462
+ /**
463
+ * Installs browser hooks before user support, including manual SDK imports.
464
+ *
465
+ * @param {object} config Cypress resolved config object
466
+ * @param {boolean} [manualLifecycle] whether the manual entry point owns lifecycle registration
467
+ * @returns {string[]|undefined} generated files owned until cleanup or process exit
468
+ */
469
+ function installSupportFile (config, manualLifecycle = false) {
470
+ const files = injectSupportFile(config, manualLifecycle)
471
+ if (files) registerGeneratedFilesForExitCleanup(files)
472
+ return files
473
+ }
474
+
475
+ /**
476
+ * Keeps early browser instrumentation in the actual manual setup return value.
477
+ *
478
+ * @param {object} config Cypress resolved config object
479
+ * @returns {(() => void)|undefined} cleanup for the one-shot setup observer
480
+ */
481
+ function installManualSupportFile (config) {
482
+ stopManualSupportSetup?.()
483
+ installSupportFile(config, true)
484
+ const originalSend = process.send
485
+ if (typeof originalSend !== 'function') return
486
+
487
+ let active = true
488
+ const stop = () => {
489
+ active = false
490
+ if (process.send === send) process.send = originalSend
491
+ if (stopManualSupportSetup === stop) stopManualSupportSetup = undefined
492
+ }
493
+ const send = function (message) {
494
+ let forwarded = message
495
+ if (active && (message?.event === 'setupTestingType:reply' || message?.event === 'setupTestingType:error')) {
496
+ try {
497
+ const reply = message.event === 'setupTestingType:reply' && message.args?.[0]
498
+ const supplied = reply?.setupConfig
499
+ if (reply && (supplied == null || (supplied && typeof supplied === 'object' && !Array.isArray(supplied)))) {
500
+ // Snapshot own enumerable values once, as native IPC serialization would.
501
+ const returnedConfig = Object.fromEntries(Object.entries(supplied ?? {}))
502
+ const supportOwner = supplied && Object.getOwnPropertyDescriptor(supplied, DD_SUPPORT_OWNER)
503
+ if (supportOwner && 'value' in supportOwner) {
504
+ Object.defineProperty(returnedConfig, DD_SUPPORT_OWNER, supportOwner)
505
+ }
506
+ const projectRoot = returnedConfig.projectRoot ?? config.projectRoot
507
+ const supportFile = returnedConfig.supportFile === undefined ? config.supportFile : returnedConfig.supportFile
508
+ // Leave invalid user configuration for Cypress's native validator.
509
+ if (typeof projectRoot === 'string' &&
510
+ (supportFile === undefined || supportFile === false || typeof supportFile === 'string')) {
511
+ const supportConfig = {
512
+ projectRoot,
513
+ supportFile: typeof supportFile === 'string' ? path.resolve(projectRoot, supportFile) : supportFile,
514
+ [DD_SUPPORT_OWNER]: returnedConfig[DD_SUPPORT_OWNER] ?? config[DD_SUPPORT_OWNER],
515
+ }
516
+ installSupportFile(supportConfig, true)
517
+ if (generatedFilesForExitCleanup.has(supportConfig.supportFile)) {
518
+ const args = [...message.args]
519
+ args[0] = {
520
+ ...reply,
521
+ setupConfig: {
522
+ ...returnedConfig,
523
+ supportFile: supportConfig.supportFile,
524
+ [DD_SUPPORT_OWNER]: supportConfig[DD_SUPPORT_OWNER],
525
+ },
526
+ }
527
+ forwarded = { ...message, args }
528
+ }
529
+ }
530
+ }
531
+ } catch (error) {
532
+ log.warn('Datadog could not retain the Cypress support wrapper in the setup reply: %s.', error)
533
+ } finally {
534
+ stop()
535
+ }
536
+ }
537
+ const args = [...arguments]
538
+ args[0] = forwarded
539
+ return originalSend.apply(this, args)
540
+ }
541
+ stopManualSupportSetup = stop
542
+ process.send = send
543
+ return stop
544
+ }
545
+
399
546
  /**
400
547
  * Registers screenshot handlers collected from a manual plugin call. User
401
548
  * handlers run first so a renamed screenshot path reaches the Datadog handler.
@@ -515,8 +662,7 @@ function registerDdTraceHooks (
515
662
  userAfterScreenshotHandlers,
516
663
  manualPlugin
517
664
  ) {
518
- const generatedSupportFiles = injectSupportFile(config)
519
- if (generatedSupportFiles) registerGeneratedFilesForExitCleanup(generatedSupportFiles)
665
+ const generatedSupportFiles = installSupportFile(config, manualPlugin.detected)
520
666
 
521
667
  const cleanupWrapper = () => {
522
668
  // Open mode reuses this support file across runs, including failed setup attempts.
@@ -930,6 +1076,8 @@ function wrapCliConfigFileOptions (options) {
930
1076
  }
931
1077
 
932
1078
  module.exports = {
1079
+ installManualSupportFile,
1080
+ installSupportFile,
933
1081
  wrapCliConfigFileOptions,
934
1082
  wrapConfig,
935
1083
  }
@@ -11,10 +11,16 @@ const { addHook, getHooks } = require('./helpers/instrument')
11
11
  * @param {string} name
12
12
  */
13
13
  function addRewriterHooks (name) {
14
- const files = new Set()
14
+ const hooks = new Map()
15
15
  for (const hook of getHooks(name).values()) {
16
- if (files.has(hook.file)) continue
17
- files.add(hook.file)
16
+ const existing = hooks.get(hook.file)
17
+ if (existing) {
18
+ existing.versions.push(...hook.versions)
19
+ } else {
20
+ hooks.set(hook.file, hook)
21
+ }
22
+ }
23
+ for (const hook of hooks.values()) {
18
24
  addHook(hook, exports => exports)
19
25
  }
20
26
  }
@@ -23,6 +23,16 @@ const isValid = (server, args) => {
23
23
  (server.type === 'unary' ? typeof args[1] === 'function' : isEmitter(args[0])))
24
24
  }
25
25
 
26
+ // A call can end through several paths (cancellation, error, handler callback);
27
+ // only the first one may finish the span and set its status. Later terminal
28
+ // events must not publish errors or status updates either: the span can still
29
+ // be buffered by an unfinished child, so they would overwrite the final tags.
30
+ function finish (ctx) {
31
+ if (ctx.finished) return
32
+ ctx.finished = true
33
+ finishChannel.publish(ctx)
34
+ }
35
+
26
36
  function wrapHandler (func, name) {
27
37
  return function (call, callback) {
28
38
  if (!isValid(this, arguments)) return func.apply(this, arguments)
@@ -37,7 +47,7 @@ function wrapHandler (func, name) {
37
47
  try {
38
48
  const onCancel = () => {
39
49
  ctx.code = CANCELLED
40
- finishChannel.publish(ctx)
50
+ finish(ctx)
41
51
  }
42
52
 
43
53
  // Finish the span if the call was cancelled.
@@ -96,12 +106,14 @@ function wrapSetupHandlers (setupHandlers) {
96
106
  function createWrapEmit (call, ctx, onCancel) {
97
107
  return function wrapEmit (emit) {
98
108
  return function (event, arg1) {
109
+ if (ctx.finished) return emit.apply(this, arguments)
110
+
99
111
  switch (event) {
100
112
  case 'error':
101
113
  ctx.error = arg1
102
114
  errorChannel.publish(ctx)
103
115
  ctx.code = arg1.code
104
- finishChannel.publish(ctx)
116
+ finish(ctx)
105
117
  call.removeListener('cancelled', onCancel)
106
118
  break
107
119
  // Streams are always cancelled before `finish` since 1.10.0 so we have
@@ -111,7 +123,7 @@ function createWrapEmit (call, ctx, onCancel) {
111
123
  updateChannel.publish(call.status)
112
124
  }
113
125
  if (!call.status || call.status.code === 0) {
114
- finishChannel.publish(ctx)
126
+ finish(ctx)
115
127
  }
116
128
  call.removeListener('cancelled', onCancel)
117
129
  break
@@ -132,6 +144,9 @@ function wrapStream (call, ctx, onCancel) {
132
144
 
133
145
  function wrapCallback (callback = () => {}, call, ctx, onCancel) {
134
146
  return shimmer.wrapFunction(callback, callback => function (err, value, trailer, flags) {
147
+ if (ctx.finished) {
148
+ return asyncStartChannel.runStores(ctx, () => callback.apply(this, arguments))
149
+ }
135
150
  if (err) {
136
151
  ctx.error = err
137
152
  errorChannel.publish(ctx)
@@ -140,7 +155,7 @@ function wrapCallback (callback = () => {}, call, ctx, onCancel) {
140
155
  ctx.trailer = trailer
141
156
  }
142
157
 
143
- finishChannel.publish(ctx)
158
+ finish(ctx)
144
159
 
145
160
  call.removeListener('cancelled', onCancel)
146
161
 
@@ -153,8 +168,10 @@ function wrapCallback (callback = () => {}, call, ctx, onCancel) {
153
168
 
154
169
  function wrapSendStatus (sendStatus, ctx) {
155
170
  return function (status) {
156
- ctx.status = status
157
- updateChannel.publish(ctx)
171
+ if (!ctx.finished) {
172
+ ctx.status = status
173
+ updateChannel.publish(ctx)
174
+ }
158
175
 
159
176
  return sendStatus.apply(this, arguments)
160
177
  }