gitlab_quality-test_tooling 3.15.0 → 3.17.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c8b4293811154f61f07fd8e35523a2406ba9832c6fe3e5eb3cf12164688df97a
4
- data.tar.gz: c31082d6308fabe29ec51b4be09ebfd5d4c1d84e61ae8b3ce3741ffadcace9a6
3
+ metadata.gz: a3a2a28593ef844ad32b920eae54b731a9981de4821ed9f9eba2776e8cad1056
4
+ data.tar.gz: f50c339ba813f7f96bc60de1b7607ef8da9667734fc1e263794a5e6e37434470
5
5
  SHA512:
6
- metadata.gz: 1e522f9897eeddf1857caa10470ab1e11ae1ad7bad5062af80dbabdfb80e0fd11170f2011a2c28e9fcf5bb59394ca5124d9a88bedca637fbaec2e2fbf462503c
7
- data.tar.gz: 1bb96de8d84feb07694145507df76707d88906b0671887b8104b79c3105859dda2c1d9ca6b68e0344478b955cdf91ec5f459ad6f1e48ca3612653b233c214531
6
+ metadata.gz: 1a4ce06d8ba98f5799aee426090cebe56eae29053febf14029300d2b9cfe9788549b0e4041e0c6f217f4db02775ce0340f836507da117ee80240354508d42204
7
+ data.tar.gz: 01ff166aa1fa3c6bcd1a8e5da11b0205c9747814c5fa8e33265cb18c37afe6366274c56f5032c32c0864b2e201269ead352d90e72aae13c6bd7e8f36aafabed0
data/AGENTS.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # gitlab_quality-test_tooling
2
2
 
3
- Ruby gem providing test tooling for GitLab CI — metrics export, test quarantine, failure reporting, flaky test tracking, and code coverage analysis.
3
+ Ruby gem providing test tooling for GitLab CI — test quarantine, failure reporting, flaky test tracking, and code coverage analysis.
4
4
 
5
5
  ## Tech Stack
6
6
 
@@ -70,11 +70,14 @@ Reference: https://docs.gitlab.com/ee/development/changelog.html
70
70
 
71
71
  ## Key Modules
72
72
 
73
- - **TestMetricsExporter** — Serializes RSpec results to ClickHouse (exception classes, failure messages, CI metadata)
74
- - **Report** — Creates/updates GitLab issues for test failures, flaky tests, slow tests
73
+ - **Report** — Creates/updates GitLab issues for test failures, flaky tests, slow tests. `RelateFailureIssue` can also trigger a GitLab Duo Agent Platform workflow to investigate newly-created failure issues (see `--duo-analysis` on `exe/relate-failure-issue`); the agent posts its analysis back as an issue comment.
75
74
  - **TestQuarantine** — RSpec formatter that skips quarantined tests
76
75
  - **CodeCoverage** — Coverage analysis and responsibility patterns
77
- - **ClickHouse::Client** — Batch HTTP client for pushing metrics
76
+ - **ClickHouse::Client** — HTTP query/insert client for ClickHouse, used by the code coverage subsystem
77
+
78
+ ## Review Guidance
79
+
80
+ - `RelateFailureIssue#trigger_duo_analysis` deliberately rescues all `StandardError` (best-effort): a Duo/API failure must never block failure-issue creation. Preserve the broad rescue — don't narrow or remove it.
78
81
 
79
82
  ## Release Process
80
83
 
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- gitlab_quality-test_tooling (3.15.0)
4
+ gitlab_quality-test_tooling (3.17.0)
5
5
  activesupport (>= 7.0)
6
6
  amatch (~> 0.4.1)
7
7
  fog-google (~> 1.24, >= 1.24.1)
data/README.md CHANGED
@@ -93,6 +93,7 @@ Usage: exe/relate-failure-issue [options]
93
93
  Labels to exclude when searching for existing issues
94
94
  --confidential Makes created new issues confidential
95
95
  --dry-run Perform a dry-run (don't create or update issues)
96
+ --duo-analysis MODES Start a GitLab Duo workflow to investigate failure issues (comma-separated modes; supported: create). Off by default
96
97
  -v, --version Show the version
97
98
  -h, --help Show the usage
98
99
  ```
@@ -66,6 +66,16 @@ options = OptionParser.new do |opts|
66
66
  params[:environment_issues_output_file] = file
67
67
  end
68
68
 
69
+ opts.on('--duo-analysis MODES', Array,
70
+ 'Start a GitLab Duo Agent Platform workflow to investigate failure issues (the agent posts its ' \
71
+ 'analysis back as a comment). Comma-separated modes; currently supported: create. Off by default.') do |modes|
72
+ supported = %w[create]
73
+ invalid = modes - supported
74
+ raise OptionParser::InvalidArgument, "#{invalid.join(',')} (supported: #{supported.join(',')})" if invalid.any?
75
+
76
+ params[:duo_analysis] = modes
77
+ end
78
+
69
79
  opts.on_tail('-v', '--version', 'Show the version') do
70
80
  require_relative "../lib/gitlab_quality/test_tooling/version"
71
81
  puts "#{$PROGRAM_NAME} : #{GitlabQuality::TestTooling::VERSION}"
data/exe/test-coverage CHANGED
@@ -12,6 +12,7 @@ require_relative '../lib/gitlab_quality/test_tooling/code_coverage/click_house/c
12
12
  require_relative '../lib/gitlab_quality/test_tooling/code_coverage/click_house/coverage_metrics_table'
13
13
  require_relative '../lib/gitlab_quality/test_tooling/code_coverage/click_house/per_test_coverage_table'
14
14
  require_relative '../lib/gitlab_quality/test_tooling/code_coverage/click_house/test_file_mappings_table'
15
+ require_relative '../lib/gitlab_quality/test_tooling/code_coverage/click_house/jest_quarantined_tests_table'
15
16
  require_relative '../lib/gitlab_quality/test_tooling/code_coverage/click_house/test_health_risk_aggregator'
16
17
  require_relative '../lib/gitlab_quality/test_tooling/code_coverage/coverage_data'
17
18
  require_relative '../lib/gitlab_quality/test_tooling/code_coverage/lcov_file'
@@ -73,6 +74,13 @@ options = OptionParser.new do |opts|
73
74
  params[:per_test_coverage] = pattern
74
75
  end
75
76
 
77
+ opts.on('--jest-quarantine-file PATH',
78
+ 'Optional. Path to quarantined_vue3_specs.txt. When provided alongside ' \
79
+ '--per-test-coverage, populates code_coverage.jest_quarantined_tests_today ' \
80
+ 'before the nightly aggregation so Jest tests count toward is_quarantined.') do |path|
81
+ params[:jest_quarantine_file] = path
82
+ end
83
+
76
84
  opts.separator ""
77
85
  opts.separator "Environment variables:"
78
86
  opts.separator " GLCI_CLICKHOUSE_METRICS_PASSWORD ClickHouse password (required, not passed via CLI for security)"
@@ -217,6 +225,13 @@ if params.any? && (required_params - params.keys).none?
217
225
  per_test_coverage_table = GitlabQuality::TestTooling::CodeCoverage::ClickHouse::PerTestCoverageTable.new(**clickhouse_data)
218
226
  per_test_coverage_table.push(per_test_data.as_db_table)
219
227
 
228
+ if params[:jest_quarantine_file] && File.exist?(params[:jest_quarantine_file])
229
+ jest_qt = GitlabQuality::TestTooling::CodeCoverage::ClickHouse::JestQuarantinedTestsTable.new(**clickhouse_data)
230
+ jest_qt.populate(quarantine_file: params[:jest_quarantine_file])
231
+ elsif params[:jest_quarantine_file]
232
+ puts "Jest quarantine file not found at #{params[:jest_quarantine_file]}; skipping jest quarantine ingestion."
233
+ end
234
+
220
235
  aggregator = GitlabQuality::TestTooling::CodeCoverage::ClickHouse::TestHealthRiskAggregator.new(**clickhouse_data)
221
236
  aggregator.run
222
237
  else
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'table'
4
+
5
+ module GitlabQuality
6
+ module TestTooling
7
+ module CodeCoverage
8
+ module ClickHouse
9
+ # Replaces `code_coverage.jest_quarantined_tests_today` with the current
10
+ # contents of `scripts/frontend/quarantined_vue3_specs.txt` before each
11
+ # nightly risk aggregation. The helper table is a transient snapshot:
12
+ # it is truncated and repopulated on every aggregation run so the
13
+ # aggregation SQL can treat it as a simple LEFT JOIN for is_quarantined
14
+ # enrichment without needing a time-windowed query.
15
+ class JestQuarantinedTestsTable
16
+ include Client
17
+
18
+ TABLE_NAME = 'jest_quarantined_tests_today'
19
+
20
+ def initialize(url:, database:, username: nil, password: nil, logger: nil)
21
+ @url = url
22
+ @database = database
23
+ @username = username
24
+ @password = password
25
+ @logger = logger || Runtime::Logger.logger
26
+ end
27
+
28
+ # Reads `quarantine_file`, truncates `jest_quarantined_tests_today`,
29
+ # then inserts one row per non-blank, non-comment line. Idempotent:
30
+ # repeated calls with the same flat file produce the same table state.
31
+ #
32
+ # @param quarantine_file [String] path to the quarantine flat file
33
+ # @return [void]
34
+ def populate(quarantine_file:)
35
+ truncate_and_insert(read_quarantine_file(quarantine_file))
36
+ rescue StandardError => e
37
+ logger.error("#{LOG_PREFIX} Error populating #{full_table_name}: #{e.message}")
38
+ raise
39
+ end
40
+
41
+ private
42
+
43
+ attr_reader :url, :database, :username, :password, :logger
44
+
45
+ def truncate_and_insert(test_files)
46
+ logger.info(
47
+ "#{LOG_PREFIX} Populating #{full_table_name} with #{test_files.size} Jest quarantined test files"
48
+ )
49
+ client.query("TRUNCATE TABLE #{full_table_name}", format: 'TabSeparated')
50
+ insert_rows(test_files) if test_files.any?
51
+ logger.info("#{LOG_PREFIX} Populated #{full_table_name} with #{test_files.size} rows")
52
+ end
53
+
54
+ def insert_rows(test_files)
55
+ rows_sql = test_files.map { |f| "('#{escape(f)}')" }.join(",\n")
56
+ client.query(<<~SQL, format: 'TabSeparated')
57
+ INSERT INTO #{full_table_name} (test_file) VALUES #{rows_sql}
58
+ SQL
59
+ end
60
+
61
+ def read_quarantine_file(path)
62
+ File.readlines(path, chomp: true)
63
+ .reject { |line| line.start_with?('#') || line.strip.empty? }
64
+ end
65
+
66
+ def full_table_name
67
+ "#{database}.#{TABLE_NAME}"
68
+ end
69
+
70
+ # ClickHouse string escape: backslash then single quote.
71
+ def escape(str)
72
+ str.to_s.gsub('\\', '\\\\\\\\').gsub("'", "''")
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end
78
+ end
@@ -71,6 +71,13 @@ WITH
71
71
  GROUP BY test_file
72
72
  HAVING is_flaky
73
73
  ),
74
+ -- Jest quarantine comes from a flat file (quarantined_vue3_specs.txt) rather
75
+ -- than the issue-based RSpec ledger. It is populated into this helper table
76
+ -- by JestQuarantinedTestsTable before each nightly aggregation run.
77
+ jest_quarantine_status AS (
78
+ SELECT test_file
79
+ FROM code_coverage.jest_quarantined_tests_today FINAL
80
+ ),
74
81
  per_test_status AS (
75
82
  SELECT
76
83
  tc.source_file,
@@ -79,11 +86,12 @@ WITH
79
86
  tc.section,
80
87
  tc.total_lines,
81
88
  tc.covered_lines,
82
- coalesce(qs.is_quarantined, FALSE) AS is_quarantined,
83
- coalesce(fs.is_flaky, FALSE) AS is_flaky
89
+ (coalesce(qs.is_quarantined, FALSE) OR (jq.test_file IS NOT NULL)) AS is_quarantined,
90
+ coalesce(fs.is_flaky, FALSE) AS is_flaky
84
91
  FROM code_coverage.test_coverage_per_file tc FINAL
85
- LEFT JOIN quarantine_status qs ON qs.test_file = tc.test_file
86
- LEFT JOIN flaky_status fs ON fs.test_file = tc.test_file
92
+ LEFT JOIN quarantine_status qs ON qs.test_file = tc.test_file
93
+ LEFT JOIN jest_quarantine_status jq ON jq.test_file = tc.test_file
94
+ LEFT JOIN flaky_status fs ON fs.test_file = tc.test_file
87
95
  WHERE tc.timestamp >= now() - INTERVAL {coverage_window}
88
96
  ),
89
97
  per_file AS (
@@ -43,6 +43,8 @@ module GitlabQuality
43
43
  # The GitLab client is used for API access: https://github.com/NARKOZ/gitlab
44
44
  class IssuesClient < GitlabClient
45
45
  REPORTER_ACCESS_LEVEL = 20
46
+ DUO_WORKFLOW_TIMEOUT = 30
47
+ DUO_WORKFLOW_DEFINITION = 'developer/v1'
46
48
 
47
49
  def assert_user_permission!
48
50
  handle_gitlab_client_exceptions do
@@ -123,6 +125,28 @@ module GitlabQuality
123
125
  end
124
126
  end
125
127
 
128
+ # Starts a GitLab Duo Agent Platform workflow (Flows API).
129
+ # The agent investigates and posts its own analysis back, so no follow-up call is needed.
130
+ #
131
+ # This is a best-effort helper: it deliberately does NOT use handle_gitlab_client_exceptions
132
+ # (which would retry with long backoffs and post failures to Slack) and uses a short timeout
133
+ # so a slow or unavailable Duo endpoint can never stall the reporting job. The caller is
134
+ # expected to rescue any error.
135
+ #
136
+ # project_id accepts either a numeric ID or a namespace path (e.g. 'gitlab-org/quality/...'),
137
+ # matching the GitLab API's project-identifier convention; the path form is verified working.
138
+ def start_duo_workflow(goal:, workflow_definition: DUO_WORKFLOW_DEFINITION, project_id: project)
139
+ client.post('/ai/duo_workflows/workflows',
140
+ timeout: DUO_WORKFLOW_TIMEOUT,
141
+ headers: { 'Content-Type' => 'application/json' },
142
+ body: {
143
+ project_id: project_id,
144
+ goal: goal,
145
+ workflow_definition: workflow_definition,
146
+ start_workflow: true
147
+ }.to_json)
148
+ end
149
+
126
150
  def edit_issue_note(issue_iid:, note_id:, note:)
127
151
  handle_gitlab_client_exceptions do
128
152
  client.edit_issue_note(project, issue_iid, note_id, note)
@@ -83,12 +83,13 @@ module GitlabQuality
83
83
  @metrics_files = Array(metrics_files)
84
84
  @group_similar = group_similar
85
85
  @environment_issues_output_file = environment_issues_output_file
86
+ @duo_analysis_modes = Array(kwargs[:duo_analysis])
86
87
  end
87
88
 
88
89
  private
89
90
 
90
91
  attr_reader :max_diff_ratio, :system_logs, :base_issue_labels, :exclude_labels_for_search, :metrics_files, :ops_gitlab_client, :group_similar,
91
- :environment_issues_output_file
92
+ :environment_issues_output_file, :duo_analysis_modes
92
93
 
93
94
  def run!
94
95
  puts "Reporting test failures in `#{files.join(',')}` as issues in project `#{project}` via the API at `#{Runtime::Env.gitlab_api_base}`."
@@ -294,9 +295,47 @@ module GitlabQuality
294
295
  # On a dry run, created_issue may not be populated
295
296
  test.failure_issue ||= created_issue&.web_url
296
297
 
298
+ trigger_duo_analysis(created_issue, test) if duo_analysis_modes.include?('create')
299
+
297
300
  created_issue
298
301
  end
299
302
 
303
+ # Best-effort: start a GitLab Duo workflow to investigate the issue; the agent comments its
304
+ # analysis back. A failure here must never block issue creation or the pipeline.
305
+ def trigger_duo_analysis(issue, test)
306
+ return unless issue&.web_url
307
+
308
+ gitlab.start_duo_workflow(goal: duo_analysis_goal(issue, test))
309
+ puts " => Triggered Duo failure analysis workflow for #{issue.web_url}"
310
+ rescue StandardError => e
311
+ warn(" => Could not trigger Duo failure analysis for #{issue.web_url} (ignored): #{e.class}: #{e.message}")
312
+ end
313
+
314
+ def duo_analysis_goal(issue, test)
315
+ <<~GOAL.chomp
316
+ Investigate the newly-reported end-to-end test failure described in this issue: #{issue.web_url}
317
+ (failing spec: `#{test.name}`). Read the issue for the failing spec and stack trace.
318
+
319
+ Investigate the `gitlab-org/gitlab` project (where the product code and E2E specs live —
320
+ note this is NOT the project hosting this issue): inspect its recent commits and merge
321
+ requests on the default branch using GitLab tools, and consult the Orbit knowledge graph
322
+ via MCP tools if it is available. Using those, identify the most likely cause of this
323
+ failure. Then post a comment on that issue with your analysis.
324
+
325
+ The failure may be caused by a product code change, or it may be environmental — for
326
+ example a flaky test, an infrastructure/environment issue, or a CI runner problem. Decide
327
+ which is more likely:
328
+
329
+ - If a specific change or merge request looks responsible, name the likely author in your
330
+ comment and ask them to confirm. Frame this as advisory ("this looks likely related —
331
+ please confirm"), never as an assertion of blame.
332
+ - If the failure looks environmental, flaky, or otherwise not attributable to a specific
333
+ change, explain why — but do not ping or attribute it to anyone.
334
+
335
+ This is an automated, best-effort request to speed up triage of newly-detected failures.
336
+ GOAL
337
+ end
338
+
300
339
  def pipeline_issues_with_similar_stacktrace(test)
301
340
  search_labels = (base_issue_labels + Set.new(%w[test failure::new])).to_a
302
341
  not_labels = exclude_labels_for_search.to_a
@@ -428,6 +467,10 @@ module GitlabQuality
428
467
  end
429
468
 
430
469
  def generate_diff_link
470
+ # Outside CI (e.g. local runs) there is no pipeline to diff against, so skip gracefully
471
+ # rather than crashing on a nil pipeline URL or an unsupported project.
472
+ return "No commit diff available (no CI pipeline context)." unless Runtime::Env.ci_pipeline_url
473
+
431
474
  initialize_gitlab_ops_client
432
475
 
433
476
  if Runtime::Env.ci_pipeline_url.include?('ops.gitlab.net')
@@ -2,6 +2,6 @@
2
2
 
3
3
  module GitlabQuality
4
4
  module TestTooling
5
- VERSION = "3.15.0"
5
+ VERSION = "3.17.0"
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: gitlab_quality-test_tooling
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.15.0
4
+ version: 3.17.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - GitLab Quality
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-05-13 00:00:00.000000000 Z
11
+ date: 2026-06-15 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: climate_control
@@ -493,6 +493,7 @@ files:
493
493
  - lib/gitlab_quality/test_tooling/code_coverage/click_house/category_owners_table.rb
494
494
  - lib/gitlab_quality/test_tooling/code_coverage/click_house/client.rb
495
495
  - lib/gitlab_quality/test_tooling/code_coverage/click_house/coverage_metrics_table.rb
496
+ - lib/gitlab_quality/test_tooling/code_coverage/click_house/jest_quarantined_tests_table.rb
496
497
  - lib/gitlab_quality/test_tooling/code_coverage/click_house/per_test_coverage_table.rb
497
498
  - lib/gitlab_quality/test_tooling/code_coverage/click_house/table.rb
498
499
  - lib/gitlab_quality/test_tooling/code_coverage/click_house/test_file_mappings_table.rb
@@ -593,11 +594,6 @@ files:
593
594
  - lib/gitlab_quality/test_tooling/test_meta/test_meta_updater.rb
594
595
  - lib/gitlab_quality/test_tooling/test_metric/json_test_metric.rb
595
596
  - lib/gitlab_quality/test_tooling/test_metrics/json_test_metric_collection.rb
596
- - lib/gitlab_quality/test_tooling/test_metrics_exporter/client.rb
597
- - lib/gitlab_quality/test_tooling/test_metrics_exporter/config.rb
598
- - lib/gitlab_quality/test_tooling/test_metrics_exporter/config_helper.rb
599
- - lib/gitlab_quality/test_tooling/test_metrics_exporter/formatter.rb
600
- - lib/gitlab_quality/test_tooling/test_metrics_exporter/test_metrics.rb
601
597
  - lib/gitlab_quality/test_tooling/test_quarantine/quarantine_formatter.rb
602
598
  - lib/gitlab_quality/test_tooling/test_quarantine/quarantine_helper.rb
603
599
  - lib/gitlab_quality/test_tooling/test_result/base_test_result.rb
@@ -1,50 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require "httparty"
4
- require "json"
5
-
6
- module GitlabQuality
7
- module TestTooling
8
- module TestMetricsExporter
9
- class Client
10
- ResponseError = Class.new(StandardError)
11
-
12
- TESTS_PATH = "/api/v1/tests"
13
- # Observer enforces a per-request cap; batch above this size to avoid silent failures.
14
- MAX_BATCH_SIZE = 10_000
15
-
16
- def initialize(url:, token:)
17
- @url = url
18
- @token = token
19
- end
20
-
21
- # POST array of test metric records to the observer service.
22
- # Wraps each batch as { "tests" => [...] } and splits oversized payloads
23
- # into chunks of at most MAX_BATCH_SIZE records.
24
- #
25
- # @param tests [Array<Hash>]
26
- # @return [Boolean] true when every batch succeeds (or input is empty)
27
- # @raise [ResponseError] on the first non-2xx batch response
28
- def post_tests(tests)
29
- tests.each_slice(MAX_BATCH_SIZE) do |batch|
30
- response = HTTParty.post(
31
- "#{url.to_s.chomp('/')}#{TESTS_PATH}",
32
- body: { tests: batch }.to_json,
33
- headers: {
34
- "X-Gitlab-Token" => token,
35
- "Content-Type" => "application/json"
36
- }
37
- )
38
- raise ResponseError, "Observer request failed with status #{response.code}: #{response.body}" unless response.success?
39
- end
40
-
41
- true
42
- end
43
-
44
- private
45
-
46
- attr_reader :url, :token
47
- end
48
- end
49
- end
50
- end
@@ -1,88 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require "logger"
4
- require "singleton"
5
-
6
- module GitlabQuality
7
- module TestTooling
8
- module TestMetricsExporter
9
- class Config
10
- include Singleton
11
-
12
- class << self
13
- def configuration
14
- Config.instance
15
- end
16
-
17
- def configure
18
- yield(configuration)
19
- end
20
- end
21
-
22
- attr_accessor :run_type,
23
- :observer_url,
24
- :observer_token
25
- attr_writer :extra_rspec_metadata_keys,
26
- :skip_record_proc,
27
- :test_retried_proc,
28
- :custom_metrics_proc,
29
- :spec_file_path_prefix,
30
- :logger
31
-
32
- # Whether observer export is configured
33
- #
34
- # Export is considered enabled when all required attributes are set
35
- #
36
- # @return [Boolean]
37
- def observer_configured?
38
- [observer_url, observer_token].none? { |value| value.nil? || value.to_s.empty? }
39
- end
40
-
41
- # Extra rspec metadata keys to include in exported metrics
42
- #
43
- # @return [Array<Symbol>]
44
- def extra_rspec_metadata_keys
45
- @extra_rspec_metadata_keys ||= []
46
- end
47
-
48
- # Extra path prefix for constructing full file path within mono-repository setups
49
- #
50
- # @return [String]
51
- def spec_file_path_prefix
52
- @spec_file_path_prefix ||= ""
53
- end
54
-
55
- # A lambda that determines whether to skip recording a test result
56
- #
57
- # This is useful when you would want to skip initial failure when retrying specs is set up in a separate process
58
- # and you want to avoid duplicate records
59
- #
60
- # @return [Proc]
61
- def skip_record_proc
62
- @skip_record_proc ||= ->(_example) { false }
63
- end
64
-
65
- # A lambda that determines whether a test was retried or not
66
- #
67
- # @return [Proc]
68
- def test_retried_proc
69
- @test_retried_proc ||= ->(_example) { false }
70
- end
71
-
72
- # A lambda that return hash with additional custom metrics
73
- #
74
- # @return [Proc]
75
- def custom_metrics_proc
76
- @custom_metrics_proc ||= ->(_example) { {} }
77
- end
78
-
79
- # Logger instance
80
- #
81
- # @return [Logger]
82
- def logger
83
- @logger ||= Logger.new($stdout, level: Logger::INFO)
84
- end
85
- end
86
- end
87
- end
88
- end
@@ -1,115 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'logger'
4
- require 'active_support/core_ext/object/blank'
5
-
6
- require_relative 'config'
7
- require_relative 'formatter'
8
-
9
- module GitlabQuality
10
- module TestTooling
11
- module TestMetricsExporter
12
- class ConfigHelper
13
- REQUIRED_OBSERVER_ENV_VARS = %w[
14
- GLCI_OBSERVER_URL
15
- GLCI_OBSERVER_AUTH_TOKEN
16
- ].freeze
17
-
18
- class << self
19
- def configure!(run_type = test_run_type)
20
- return unless ENV.fetch("CI", nil) && ENV.fetch("GLCI_EXPORT_TEST_METRICS", "true") == "true" && run_type
21
-
22
- RSpec.configure do |rspec_config|
23
- next if rspec_config.dry_run?
24
-
25
- Config.configure do |exporter_config|
26
- self.logger = exporter_config.logger
27
- next warn_missing_observer_variables unless observer_env_vars_present?
28
-
29
- yield(exporter_config) if block_given?
30
- configure_exporter!(exporter_config, run_type)
31
-
32
- rspec_config.add_formatter Formatter
33
-
34
- logger.info("Test metrics export is enabled for run type: #{run_type}")
35
- end
36
- end
37
- end
38
-
39
- private
40
-
41
- attr_writer :logger
42
-
43
- def logger
44
- @logger ||= Logger.new($stdout)
45
- end
46
-
47
- def observer_env_vars_present?
48
- REQUIRED_OBSERVER_ENV_VARS.all? { |var| ENV.fetch(var, nil) && !ENV[var].empty? }
49
- end
50
-
51
- def configure_exporter!(config, run_type)
52
- config.run_type = run_type
53
- config.custom_metrics_proc = custom_metrics_proc
54
-
55
- configure_observer!(config)
56
- end
57
-
58
- def configure_observer!(config)
59
- config.observer_url = observer_url
60
- config.observer_token = observer_token
61
- end
62
-
63
- def warn_missing_observer_variables
64
- missing = REQUIRED_OBSERVER_ENV_VARS.reject { |var| ENV.fetch(var, nil) && !ENV[var].empty? }
65
- logger.warn("Test metrics export is enabled but missing environment variables: #{missing.join(', ')}")
66
- end
67
-
68
- def custom_metrics_proc
69
- proc do |_example|
70
- { pipeline_type: pipeline_type, ci_pipeline_id: ci_pipeline_id }
71
- end
72
- end
73
-
74
- def default_branch?
75
- ENV["CI_COMMIT_REF_NAME"] == ENV["CI_DEFAULT_BRANCH"]
76
- end
77
-
78
- def pipeline_type
79
- @pipeline_type ||= if default_branch? && ENV["SCHEDULE_TYPE"].present?
80
- "default_branch_scheduled_pipeline"
81
- elsif default_branch?
82
- "default_branch_pipeline"
83
- elsif ENV["CI_COMMIT_REF_NAME"]&.match?(/^[\d-]+-stable-ee$/)
84
- "stable_branch_pipeline"
85
- elsif ENV["CI_MERGE_REQUEST_TARGET_BRANCH_NAME"]&.match?(/^[\d-]+-stable-ee$/)
86
- "backport_merge_request_pipeline"
87
- elsif ENV["CI_MERGE_REQUEST_IID"].present?
88
- "merge_request_pipeline"
89
- elsif ENV["CI_PIPELINE_SOURCE"] == "pipeline"
90
- "downstream_pipeline"
91
- else
92
- "unknown"
93
- end
94
- end
95
-
96
- def test_run_type
97
- @run_type ||= ENV.fetch("GLCI_TEST_METRICS_RUN_TYPE", nil)
98
- end
99
-
100
- def observer_url
101
- ENV.fetch("GLCI_OBSERVER_URL", nil)
102
- end
103
-
104
- def observer_token
105
- ENV.fetch("GLCI_OBSERVER_AUTH_TOKEN", nil)
106
- end
107
-
108
- def ci_pipeline_id
109
- (ENV["PARENT_PIPELINE_ID"] || ENV.fetch("CI_PIPELINE_ID", nil)).to_i
110
- end
111
- end
112
- end
113
- end
114
- end
115
- end
@@ -1,67 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require "rspec/core/formatters/base_formatter"
4
-
5
- require_relative "test_metrics"
6
- require_relative "client"
7
-
8
- module GitlabQuality
9
- module TestTooling
10
- module TestMetricsExporter
11
- class Formatter < RSpec::Core::Formatters::BaseFormatter
12
- RSpec::Core::Formatters.register(self, :stop)
13
-
14
- LOG_PREFIX = "[MetricsExporter]"
15
-
16
- def stop(notification)
17
- logger.debug("#{LOG_PREFIX} Starting test metrics export")
18
- data = notification.examples.filter_map do |example|
19
- next if config.skip_record_proc.call(example)
20
-
21
- TestMetrics.new(example, time).data
22
- end
23
- return logger.warn("#{LOG_PREFIX} No test execution records found, metrics will not be exported!") if data.empty?
24
-
25
- push_to_observer(data)
26
- end
27
-
28
- private
29
-
30
- def config
31
- Config.configuration
32
- end
33
-
34
- def logger
35
- config.logger
36
- end
37
-
38
- # Single common timestamp for all exported example metrics to keep data points consistently grouped
39
- #
40
- # @return [String]
41
- def time
42
- return @time if @time
43
-
44
- ci_created_at = ENV.fetch("CI_PIPELINE_CREATED_AT", nil)
45
- @time = (ci_created_at ? Time.strptime(ci_created_at, '%Y-%m-%dT%H:%M:%S%z') : Time.now.utc).strftime('%Y-%m-%dT%H:%M:%S.%6N')
46
- end
47
-
48
- # Push data to observer service
49
- #
50
- # @param data [Array<Hash>]
51
- # @return [void]
52
- def push_to_observer(data)
53
- return logger.debug("#{LOG_PREFIX} Observer configuration missing, skipping export!") unless config.observer_configured?
54
-
55
- observer_client.post_tests(data)
56
- logger.info("#{LOG_PREFIX} Successfully pushed #{data.size} entries to Observer!")
57
- rescue StandardError => e
58
- logger.error("#{LOG_PREFIX} Error occurred while pushing metrics to Observer: #{e.message}")
59
- end
60
-
61
- def observer_client
62
- Client.new(url: config.observer_url, token: config.observer_token)
63
- end
64
- end
65
- end
66
- end
67
- end
@@ -1,228 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'time'
4
-
5
- module GitlabQuality
6
- module TestTooling
7
- module TestMetricsExporter
8
- class TestMetrics
9
- def initialize(example, timestamp)
10
- @example = example
11
- @timestamp = timestamp
12
- end
13
-
14
- # Test data hash
15
- #
16
- # @return [Hash]
17
- def data
18
- {
19
- timestamp: timestamp,
20
- **rspec_metrics,
21
- **ci_metrics,
22
- **custom_metrics
23
- }.compact
24
- end
25
-
26
- private
27
-
28
- attr_reader :example, :timestamp
29
-
30
- # Exporter configuration
31
- #
32
- # @return [Config]
33
- def config
34
- Config.configuration
35
- end
36
-
37
- # Rspec related metrics
38
- #
39
- # @return [Hash]
40
- def rspec_metrics # rubocop:disable Metrics/AbcSize
41
- {
42
- id: without_relative_path(example.id),
43
- name: example.full_description,
44
- hash: OpenSSL::Digest.hexdigest("SHA256", "#{file_path}#{example.full_description}")[..40],
45
- file_path: file_path,
46
- status: example.execution_result.status,
47
- run_time: (example.execution_result.run_time * 1000).round,
48
- location: example_location,
49
- # TODO: remove exception_class once migration to exception_classes is fully complete on clickhouse side
50
- exception_class: example.execution_result.exception&.class&.to_s,
51
- exception_classes: exception_classes.map { |e| e.class.to_s }.uniq,
52
- failure_exception: failure_exception,
53
- quarantined: quarantined?,
54
- quarantine_issue_url: quarantine_issue_url || "",
55
- feature_category: example.metadata[:feature_category] || "",
56
- test_retried: config.test_retried_proc.call(example),
57
- run_type: run_type,
58
- spec_file_path_prefix: config.spec_file_path_prefix
59
- }
60
- end
61
-
62
- # CI related metrics
63
- #
64
- # @return [Hash]
65
- def ci_metrics
66
- {
67
- ci_project_id: env("CI_PROJECT_ID")&.to_i,
68
- ci_project_path: env("CI_PROJECT_PATH"),
69
- ci_job_name: ci_job_name,
70
- ci_job_id: env('CI_JOB_ID')&.to_i,
71
- ci_pipeline_id: env('CI_PIPELINE_ID')&.to_i,
72
- ci_merge_request_iid: (env('CI_MERGE_REQUEST_IID') || env('TOP_UPSTREAM_MERGE_REQUEST_IID'))&.to_i,
73
- ci_branch: env("CI_COMMIT_REF_NAME"),
74
- ci_target_branch: env("CI_MERGE_REQUEST_TARGET_BRANCH_NAME"),
75
- ci_server_url: env("CI_SERVER_URL")
76
- }
77
- end
78
-
79
- # Additional custom metrics
80
- #
81
- # @return [Hash]
82
- def custom_metrics
83
- metrics = example.metadata
84
- .slice(*config.extra_rspec_metadata_keys)
85
- .merge(config.custom_metrics_proc.call(example))
86
-
87
- metrics.each_with_object({}) do |(k, value), custom_metrics|
88
- custom_metrics[k.to_sym] = metrics_value(value)
89
- end
90
- end
91
-
92
- # Checks if spec is quarantined
93
- #
94
- # @return [String]
95
- def quarantined?
96
- return false unless example.metadata.key?(:quarantine)
97
-
98
- # if quarantine key is present and status is pending, consider it quarantined
99
- example.execution_result.status == :pending
100
- end
101
-
102
- # Extract quarantine issue URL from metadata
103
- #
104
- # @return [String, nil]
105
- def quarantine_issue_url
106
- return nil unless example.metadata.key?(:quarantine)
107
-
108
- metadata = example.metadata[:quarantine]
109
- case metadata
110
- when String
111
- # Direct URL: quarantine: 'https://gitlab.com/.../issues/123'
112
- metadata if metadata.start_with?('http')
113
- when Hash
114
- # Hash format: quarantine: { issue: 'https://...', reason: '...' }
115
- issue = metadata[:issue] || metadata['issue']
116
- # Handle array of URLs (take the first one)
117
- issue.is_a?(Array) ? issue.first : issue
118
- end
119
- end
120
-
121
- # Base ci job name
122
- #
123
- # @return [String]
124
- def ci_job_name
125
- env("CI_JOB_NAME")&.gsub(%r{ \d{1,2}/\d{1,2}}, '')
126
- end
127
-
128
- # Example location
129
- #
130
- # @return [String]
131
- def example_location
132
- return @example_location if @example_location
133
-
134
- # ensures that location will be correct even in case of shared examples
135
- file = example
136
- .metadata
137
- .fetch(:shared_group_inclusion_backtrace)
138
- .last
139
- &.formatted_inclusion_location
140
-
141
- return without_relative_path(example.location) unless file
142
-
143
- @example_location = without_relative_path(file)
144
- end
145
-
146
- # File path based on actual test location, not shared example location
147
- #
148
- # @return [String]
149
- def file_path
150
- @file_path ||= example_location.gsub(/:\d+$/, "")
151
- end
152
-
153
- # Failure exception classes
154
- #
155
- # @return [Array<Exception>]
156
- def exception_classes
157
- exception = example.execution_result.exception
158
- return [] unless exception
159
- return [exception] unless exception.respond_to?(:all_exceptions)
160
-
161
- exception.all_exceptions.flatten
162
- end
163
-
164
- # Truncated exception message
165
- #
166
- # For MultipleExceptionError, returns the first wrapped exception's message
167
- # instead of the unhelpful wrapper class name.
168
- #
169
- # @return [String]
170
- def failure_exception
171
- exception = example.execution_result.exception
172
- return unless exception
173
-
174
- source = if exception.respond_to?(:all_exceptions)
175
- exception.all_exceptions.flatten.first || exception
176
- else
177
- exception
178
- end
179
-
180
- source.to_s.tr("\n", " ").slice(0, 1000)
181
- end
182
-
183
- # Test run type | suite name
184
- #
185
- # @return [String]
186
- def run_type
187
- config.run_type || ci_job_name || "unknown"
188
- end
189
-
190
- # Return non empty environment variable value
191
- #
192
- # @param [String] name
193
- # @return [String, nil]
194
- def env(name)
195
- return unless ENV[name] && !ENV[name].empty?
196
-
197
- ENV.fetch(name)
198
- end
199
-
200
- # Metrics value cast to a valid type
201
- #
202
- # @param value [Object]
203
- # @return [Object]
204
- def metrics_value(value)
205
- return value if value.is_a?(Numeric) || value.is_a?(String) || bool?(value) || value.nil?
206
-
207
- value.to_s
208
- end
209
-
210
- # Value is a true or false
211
- #
212
- # @param val [Object]
213
- # @return [Boolean]
214
- def bool?(val)
215
- [true, false].include?(val)
216
- end
217
-
218
- # Path without leading ./
219
- #
220
- # @param path [String]
221
- # @return [String]
222
- def without_relative_path(path)
223
- path.gsub(%r{^\./}, "")
224
- end
225
- end
226
- end
227
- end
228
- end