buildkite-test_collector 2.16.0 → 2.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: 83d45811e314ed3a6defa2daebb928af60cf113a555e0409c5a842ad44cf0385
4
- data.tar.gz: bb1687220b76611bb509f12d1804bf9ec530423e55b66a89cfd4ac0bb66acfd4
3
+ metadata.gz: f40dec372895345d99af434be7e214f1cc9009643a904b20f78d7bb158be935d
4
+ data.tar.gz: ac03c35d84ba8bb8c80fa850284f3a29387861872503d1bc9419de85d7b74f6a
5
5
  SHA512:
6
- metadata.gz: 42527c632311eafe2cc64e48b92b3a4da9e148b0a32fb72a687393f7ccf227cbee57be3fc8e50ba555844ef3d27e9dfae8b923285588ccf8cd0c635f9e92baab
7
- data.tar.gz: 554ca53a2271210bdc6c796187f60bc5069038c98137514c156c5d9f0ef877767608a4d44d6f9357687c4892e7743e55550ca49e097bb08099cefdcc5872dfc4
6
+ metadata.gz: c2a1da6bb295a35862e55e31c99551484d21adedf5e9cc4b71e2387a6480097640314b746c7927b86847737435ba0e7a5e2153640627716489c8e50707b72b27
7
+ data.tar.gz: 57646e4a9e9f13045e257a838f450f43331c24c9f6f6161168bfa36687bff5586cef1abff0525232df99006fbfeebf5167bfcf18882ab806b35d571d3feecc96
data/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## Unreleased
4
+
5
+ ## v2.17.0
6
+
7
+ * Export an OpenTelemetry `test.execution` span for examples that RSpec fails
8
+ without running them, such as every example under a failing
9
+ `before(:context)` hook. These spans carry the failure but time only its
10
+ reporting and have no phase spans.
11
+ * Keep OpenTelemetry test span and event attributes (execution identity, result,
12
+ and failure detail) when the process sets `OTEL_ATTRIBUTE_COUNT_LIMIT`,
13
+ `OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`, or `OTEL_EVENT_ATTRIBUTE_COUNT_LIMIT`
14
+ below the collector's needs.
15
+ * `buildkite-rspec` writes formatter `--out` files per batch instead of
16
+ overwriting them, so earlier batches' output is no longer lost. A `%{batch}`
17
+ placeholder in the path is replaced with the batch ID; otherwise the file name
18
+ is prefixed with it (`--out tmp/rspec.json` writes `tmp/<batch>-rspec.json`).
19
+ This applies to command-line and options-file formatters.
20
+
21
+ * Add `test.setup`, `test.body`, and `test.teardown` phase spans under each
22
+ OpenTelemetry `test.execution` span. Instrumented child spans nest under the
23
+ phase they ran in, each phase records its failures, and phase spans bypass
24
+ `otel_span_filter`. Only phases that grouped a span or failed are exported,
25
+ so examples with no instrumented work add no child spans.
26
+ `Buildkite::TestCollector.annotate` records on the `test.execution` span
27
+ rather than the current span, and does nothing outside an example.
28
+ * Send a `Buildkite-Tests-Span-Stream` header on every OpenTelemetry export:
29
+ `test` on requests carrying `test.execution` spans and `child` on requests
30
+ carrying child and phase spans. Relays between the collector and Buildkite
31
+ should forward it.
32
+
3
33
  ## v2.16.0
4
34
 
5
35
  * Report `code.line.number` for shared example inclusions (`it_behaves_like`,
data/README.md CHANGED
@@ -87,8 +87,11 @@ Add the `BUILDKITE_ANALYTICS_TOKEN` secret to your CI, push your changes to a br
87
87
 
88
88
  RSpec suites can submit each test execution as an OpenTelemetry trace. Each
89
89
  trace is rooted in a `test.execution` span carrying the test's name, location,
90
- result, and failure detail. Instrumented child spans show what the test did and
91
- where it spent its time.
90
+ result, and failure detail. Phase spans underneath it, `test.setup`,
91
+ `test.body`, and `test.teardown`, group the instrumented child spans by whether
92
+ they ran in before hooks, the example itself, or after hooks, and each records
93
+ the failure raised in its phase. A phase with no spans and no failure is not
94
+ exported.
92
95
 
93
96
  This feature is still under development and may change. OpenTelemetry is off by
94
97
  default. Enable it when you configure the collector:
@@ -23,6 +23,8 @@ Gem::Specification.new do |spec|
23
23
  `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
24
24
  end
25
25
  spec.require_paths = ["lib"]
26
+ spec.bindir = "exe"
27
+ spec.executables = ["buildkite-rspec"]
26
28
 
27
29
  spec.required_ruby_version = Gem::Requirement.new(">= 3.0.0")
28
30
 
@@ -32,15 +32,33 @@ shown in [Choosing instrumentation](#choosing-instrumentation).
32
32
 
33
33
  ## What a trace looks like
34
34
 
35
- Each example gets a `test.execution` span of its own, with the instrumented work
36
- it did underneath:
35
+ Each example gets a `test.execution` span of its own. Under it are up to three
36
+ phase spans, and the instrumented work nests under the phase it ran in:
37
37
 
38
38
  ```text
39
39
  test.execution "Buildkite::Pipeline creates a build" 12.4ms
40
- ├── GET api.example.com 8.1ms
41
- └── SELECT pipelines 1.2ms
40
+ ├── test.setup 2.0ms
41
+ │ └── INSERT pipelines 1.2ms
42
+ ├── test.body 9.9ms
43
+ │ ├── GET api.example.com 8.1ms
44
+ │ └── SELECT builds 0.9ms
45
+ └── test.teardown 0.5ms
46
+ └── DELETE pipelines 0.4ms
42
47
  ```
43
48
 
49
+ `test.setup` covers `before(:each)` hooks and `let!`, `test.body` the example
50
+ block, and `test.teardown` `after(:each)` hooks and mock verification. A phase
51
+ whose failure fails the example gets an error status and an `exception` event
52
+ per failure, so a trace shows which phase failed even before you read the
53
+ test's own error. A before hook that raises leaves no `test.body` span, because
54
+ RSpec never runs the example. `around` hooks wrap all three phases, so spans
55
+ they open stay direct children of the test span, alongside the phases.
56
+
57
+ A phase is exported only when it grouped at least one span or failed; a phase
58
+ with nothing in it says nothing the test span does not. An example with no
59
+ instrumented work therefore adds no child spans at all, and `otel_span_filter`
60
+ never sees phase spans.
61
+
44
62
  One example is one trace. Child spans share the root's trace ID, and the root is
45
63
  never nested under anything else, so a trace always belongs to exactly one test.
46
64
  On Buildkite Agent v3.110 or newer, the test span links to the Agent's propagated
@@ -59,6 +77,14 @@ Three things worth knowing:
59
77
  failure, and an example a hook marks `pending` before deliberately raising
60
78
  stays skipped.
61
79
 
80
+ Failures that bypass the collector's per-example hook still get a result span.
81
+ For example, a failing `before(:context)` produces one failed execution for each
82
+ affected example, and an outer `around` hook can fail before calling `example.run`.
83
+ Those spans are created when RSpec reports the failure: they retain test identity
84
+ and failure details, but time only result reporting, not the failed hook, and
85
+ have no phase spans. Suite-level failures without an example result (such as
86
+ `before(:suite)` failures or spec load errors) do not produce test executions.
87
+
62
88
  ## OTLP execution attributes
63
89
 
64
90
  The `buildkite.execution.via=otlp` marker opts every exported test span
@@ -185,9 +211,10 @@ configure instrumentation there as you normally would. This is also the way to
185
211
  keep a bundle full of instrumentation gems (such as
186
212
  `opentelemetry-instrumentation-all`, loaded for production) unpatched under
187
213
  test: configure the SDK yourself, before the suite starts, without `use` or
188
- `use_all`, and the collector forwards only `test.execution` spans and any spans
189
- your suite creates by hand. Set `OTEL_TRACES_EXPORTER=none` as well, or the
190
- SDK adds its own default OTLP exporter aimed at `localhost:4318`:
214
+ `use_all`, and the collector forwards only `test.execution` spans, the phase
215
+ spans, and any spans your suite creates by hand. Set `OTEL_TRACES_EXPORTER=none`
216
+ as well, or the SDK adds its own default OTLP exporter aimed at
217
+ `localhost:4318`:
191
218
 
192
219
  ```ruby
193
220
  # spec/spec_helper.rb
@@ -204,6 +231,9 @@ Buildkite::TestCollector.configure(hook: :rspec, otel_enabled: true)
204
231
 
205
232
  Child spans from a suite-owned provider keep that provider's resource rather
206
233
  than the collector's (see [OTLP execution attributes](#otlp-execution-attributes)).
234
+ The collector also creates the phase spans on that provider, so any exporter of
235
+ your own attached to it receives `test.setup`, `test.body`, and `test.teardown`
236
+ spans for every example, empty or not, without their `test.execution` parent.
207
237
  The collector does not inspect instrumentation patches, so compatibility
208
238
  between the instrumentation you install and other APM or test-library patches
209
239
  remains your responsibility.
@@ -248,9 +278,10 @@ Buildkite::TestCollector.configure(
248
278
  ```
249
279
 
250
280
  The filter only sees child spans that belong to a test span; `test.execution`
251
- spans themselves are never filtered. A broken filter never costs you spans: if
252
- it raises or cannot be called with a span, the collector retains that span and
253
- warns on the first failure.
281
+ spans and the `test.setup`, `test.body`, and `test.teardown` phase spans are
282
+ never filtered. A broken filter never costs you spans: if it raises or cannot be
283
+ called with a span, the collector retains that span and warns on the first
284
+ failure.
254
285
 
255
286
  The filter runs on whichever thread finishes each span, so it can be called
256
287
  concurrently and should not depend on shared mutable state. Spans that finish
@@ -275,6 +306,13 @@ listener and local credential, then forwards spans to Buildkite with its OIDC
275
306
  credential. `Buildkite-Tests-Run-Key` always carries the run key from the test
276
307
  spans.
277
308
 
309
+ Every request also carries `Buildkite-Tests-Span-Stream`: `test` for batches of
310
+ `test.execution` spans and `child` for batches of child spans, including the
311
+ `test.setup`, `test.body`, and `test.teardown` phase spans. A request never
312
+ mixes the two. If you relay collector traffic through your own OTLP proxy
313
+ before it reaches Buildkite, forward this header along with
314
+ `Buildkite-Tests-Run-Key`.
315
+
278
316
  The standard `OTEL_EXPORTER_OTLP_*` endpoint and header variables are never
279
317
  read, so credentials the process configures for another OpenTelemetry
280
318
  destination are not sent to Buildkite, and that destination's settings do not
@@ -364,8 +402,11 @@ identity and history as the JSON upload. The collector also caps the failure
364
402
  reason in the span status at 1,024 characters and each exception message at
365
403
  10,243 characters, the server's failure summary and message quotas; stack traces
366
404
  keep the 16,384-character event limit because the server keeps up to 100 KiB of
367
- stack trace per execution. These limits ignore the process-wide `OTEL_SPAN_*`
368
- and `OTEL_EVENT_*` settings; attribute and link count limits keep SDK defaults.
405
+ stack trace per execution. Test spans and their events each keep up to 128
406
+ attributes. These length and count limits ignore the process-wide `OTEL_SPAN_*`,
407
+ `OTEL_EVENT_*`, and `OTEL_ATTRIBUTE_COUNT_LIMIT` settings, so an application's
408
+ limits cannot strip execution identity, results, or failure detail; link limits
409
+ keep the SDK defaults and environment settings.
369
410
 
370
411
  These settings do not guarantee that requests fit the server limits. Request
371
412
  bodies over 900 KiB are rejected with HTTP 413 and logged by the exporter.
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "buildkite/rspec_runner"
5
+
6
+ exit Buildkite::RSpecRunner.run
@@ -0,0 +1,301 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rspec/core"
4
+ require "socket"
5
+ require "securerandom"
6
+ require "tempfile"
7
+ require_relative "test_collector"
8
+
9
+ module Buildkite
10
+ # A work-source-agnostic client. bktec owns retries, muting and job status.
11
+ class RSpecRunner
12
+ class Error < StandardError; end
13
+
14
+ DONE_REASONS = %w[plan_completed pool_consumed pool_errored terminating error].freeze
15
+ SOCKET_ENV = "BUILDKITE_TEST_ENGINE_RUNNER_SOCKET"
16
+ BATCH_PLACEHOLDER = "%{batch}"
17
+
18
+ class Client
19
+ attr_accessor :session_id, :read_timeout
20
+
21
+ def initialize(path)
22
+ @path = path
23
+ @read_timeout = 35
24
+ end
25
+
26
+ def interrupt
27
+ @interrupted = true
28
+ @socket&.close
29
+ end
30
+
31
+ def request(method, path, payload, expected: 200)
32
+ # Serialize once: after a lost response the host accepts only an exact replay.
33
+ body = JSON.generate(payload)
34
+ attempts = 0
35
+
36
+ begin
37
+ @socket = socket = UNIXSocket.new(@path)
38
+ io = Net::BufferedIO.new(socket, read_timeout: read_timeout, write_timeout: 35)
39
+
40
+ request = Net::HTTPGenericRequest.new(method, true, true, "/v1#{path}", {
41
+ "Host" => "localhost", "Content-Type" => "application/json", "Connection" => "close",
42
+ })
43
+ # The initial handshake has no session; bktec assigns it in the response.
44
+ request["X-Bktec-Session"] = session_id if session_id
45
+ request.body = body
46
+ request.exec(io, "1.1", "/v1#{path}")
47
+
48
+ response = Net::HTTPResponse.read_new(io)
49
+ response.reading_body(io, true) { response.body }
50
+ raise Error, "#{method} #{path}: HTTP #{response.code}" unless response.code.to_i == expected
51
+
52
+ value = JSON.parse(response.body)
53
+ raise Error, "#{method} #{path}: expected a JSON object" unless value.is_a?(Hash)
54
+ value
55
+ rescue EOFError, IOError, SystemCallError, Net::ReadTimeout, Net::WriteTimeout
56
+ socket&.close
57
+ retry if !@interrupted && (attempts += 1) < 3
58
+ raise
59
+ ensure
60
+ socket&.close
61
+ @socket = nil
62
+ end
63
+ end
64
+ end
65
+
66
+ def self.run(args = ARGV)
67
+ new.run(args)
68
+ end
69
+
70
+ def run(args)
71
+ validate_options!(args)
72
+
73
+ path = ENV.fetch(SOCKET_ENV) { raise Error, "#{SOCKET_ENV} is required" }
74
+ raise Error, "#{SOCKET_ENV} must not be empty" if path.empty?
75
+
76
+ @client = Client.new(path)
77
+ install_signals
78
+
79
+ puts "[buildkite-rspec] Booting RSpec application..."
80
+ $stdout.flush
81
+ boot_application
82
+ return 1 if @stopping
83
+
84
+ start_session
85
+
86
+ until @stopping
87
+ work = @client.request("POST", "/batches", {})
88
+ break if @stopping
89
+
90
+ case work["type"]
91
+ when "batch"
92
+ execute_batch(work.fetch("batch"))
93
+ when "wait"
94
+ delay = work["retry_after_ms"]
95
+ raise Error, "invalid retry_after_ms" unless delay.is_a?(Integer) && delay >= 0
96
+
97
+ # Short sleeps let signals stop the wait promptly.
98
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + delay / 1000.0
99
+ sleep(0.05) until @stopping || Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
100
+ when "done"
101
+ raise Error, "unknown done reason" unless DONE_REASONS.include?(work["reason"])
102
+
103
+ flush_collector
104
+ return 0
105
+ else
106
+ raise Error, "unknown work response type"
107
+ end
108
+ end
109
+ 1
110
+ rescue StandardError, LoadError, SyntaxError => e
111
+ warn "[buildkite-rspec] #{e.class}: #{e.message}"
112
+ 1
113
+ ensure
114
+ begin
115
+ flush_collector
116
+
117
+ # A signal leaves the current batch unresolved rather than accepting partial work.
118
+ if @client&.session_id && @stopping
119
+ @client.request("DELETE", "/sessions/#{@client.session_id}", { reason: "signal_#{@stopping.downcase}" })
120
+ end
121
+ rescue StandardError => e
122
+ warn "[buildkite-rspec] cleanup failed: #{e.message}"
123
+ ensure
124
+ @previous_signals&.each { |signal, handler| Signal.trap(signal, handler) }
125
+ end
126
+ end
127
+
128
+ private
129
+
130
+ def boot_application
131
+ # Load the project's configured RSpec requires before asking for work.
132
+ $LOAD_PATH.unshift(File.expand_path("spec")) unless $LOAD_PATH.include?(File.expand_path("spec"))
133
+ @options.fetch(:libs, []).reverse_each { |dir| $LOAD_PATH.unshift(File.expand_path(dir)) }
134
+ @options.fetch(:requires, []).each { |file| require file }
135
+
136
+ # Preserve application collector settings, or install the default RSpec hooks.
137
+ Buildkite::TestCollector.configure(hook: :rspec) unless Buildkite::TestCollector.test_runner
138
+ validate_configuration!
139
+ end
140
+
141
+ def start_session
142
+ session = @client.request("POST", "/sessions", {
143
+ instance_id: SecureRandom.uuid,
144
+ runner: { name: "buildkite-rspec", version: Buildkite::TestCollector::VERSION,
145
+ framework: "rspec", framework_version: RSpec::Core::Version::STRING,
146
+ language: "ruby", language_version: RUBY_VERSION, pid: Process.pid },
147
+ capabilities: { selector_formats: %w[selector file example] },
148
+ }, expected: 201)
149
+ @client.session_id = nonempty_string!(session["session_id"], "session_id")
150
+
151
+ # Allow a little longer than the host's maximum long-poll duration.
152
+ max_wait = session.fetch("poll").fetch("max_wait_ms")
153
+ raise Error, "invalid poll max_wait_ms" unless max_wait.is_a?(Integer) && max_wait >= 0
154
+ @client.read_timeout = max_wait / 1000.0 + 5
155
+ end
156
+
157
+ def validate_options!(args)
158
+ unless ENV.fetch("SPEC_OPTS", "").strip.empty?
159
+ raise Error, "SPEC_OPTS is incompatible with the persistent runner"
160
+ end
161
+
162
+ @rspec_args = args.dup
163
+ @options = RSpec::Core::ConfigurationOptions.new(@rspec_args).options
164
+
165
+ unless @options.fetch(:files_or_directories_to_run, []).empty?
166
+ raise Error, "caller selectors are not supported; bktec supplies batches"
167
+ end
168
+
169
+ if @options[:dry_run]
170
+ raise Error, "--dry-run is incompatible with persistent batches: assigned tests must execute"
171
+ end
172
+
173
+ # Additional formatters are allowed, but cannot replace the private JSON
174
+ # report appended by execute_batch. Work selection belongs to the host.
175
+ safe = [:libs, :requires, :color, :color_mode, :order, :seed, :warnings,
176
+ :backtrace, :custom_options_file, :formatters, :files_or_directories_to_run]
177
+ invalid = @options.keys - safe
178
+ raise Error, "incompatible persistent RSpec options: #{invalid.join(', ')}" unless invalid.empty?
179
+ end
180
+
181
+ def validate_configuration!
182
+ config = RSpec.configuration
183
+ unless Buildkite::TestCollector.test_runner == "rspec"
184
+ raise Error, "the collector must use the rspec hook"
185
+ end
186
+
187
+ if defined?(RSpec::Retry)
188
+ raise Error, "rspec-retry is incompatible with the persistent runner; bktec owns retries"
189
+ end
190
+
191
+ if config.dry_run || config.fail_fast || config.only_failures ||
192
+ !config.inclusion_filter.empty? || !config.exclusion_filter.empty?
193
+ raise Error, "RSpec filtering, dry_run, only_failures and fail_fast are incompatible with persistent batches"
194
+ end
195
+ end
196
+
197
+ def install_signals
198
+ @previous_signals = {}
199
+ %w[INT TERM].each do |signal|
200
+ @previous_signals[signal] = Signal.trap(signal) do
201
+ @stopping = signal
202
+ RSpec.world.wants_to_quit = true
203
+ @client.interrupt
204
+ end
205
+ end
206
+ end
207
+
208
+ def nonempty_string!(value, name)
209
+ raise Error, "invalid #{name}" unless value.is_a?(String) && !value.empty?
210
+ value
211
+ end
212
+
213
+ def build_rspec_selectors(batch)
214
+ tests = batch.fetch("tests")
215
+ raise Error, "batch tests must be a nonempty array" unless tests.is_a?(Array) && !tests.empty?
216
+ tests.map do |test|
217
+ value = case test.fetch("format")
218
+ when "selector" then test["value"]
219
+ when "file" then test["path"]
220
+ when "example" then test["identifier"].to_s.empty? ? test["path"] : test["identifier"]
221
+ else raise Error, "unsupported selector format"
222
+ end
223
+ nonempty_string!(value, "test selector")
224
+ raise Error, "test selector cannot be an option" if value.start_with?("-")
225
+ value
226
+ end
227
+ end
228
+
229
+ def execute_batch(batch)
230
+ id = nonempty_string!(batch.fetch("id"), "batch id")
231
+ # Batch IDs are opaque path segments, not URL paths.
232
+ path = "/batches/#{URI.encode_www_form_component(id)}/results"
233
+ args = build_rspec_selectors(batch)
234
+
235
+ reset_batch
236
+ puts "[buildkite-rspec] Running batch #{id}:"
237
+ args.each { |selector| puts "[buildkite-rspec] #{selector}" }
238
+ $stdout.flush
239
+
240
+ Tempfile.create(["bktec-rspec-", ".json"]) do |report|
241
+ options = RSpec::Core::ConfigurationOptions.new(@rspec_args + args)
242
+ # RSpec truncates formatter files when it opens them, so give each batch
243
+ # its own files, then add the private native report.
244
+ options.options[:formatters] = options.options.fetch(:formatters, []).map do |formatter, output|
245
+ output ? [formatter, batch_output_path(output, id)] : [formatter]
246
+ end + [["json", report.path]]
247
+
248
+ begin
249
+ # Runner.run would install its own INT trap; ours stops cooperatively.
250
+ RSpec::Core::Runner.new(options).run($stderr, $stdout)
251
+ return if @stopping # Partial reports must not acknowledge outstanding work.
252
+
253
+ native_report = JSON.parse(File.read(report.path))
254
+ raise Error, "RSpec report is not an object" unless native_report.is_a?(Hash)
255
+ rescue StandardError, LoadError, SyntaxError => e
256
+ return if @stopping
257
+
258
+ @client.request("POST", path, {
259
+ status: "errored", report_format: "rspec-json",
260
+ error: { kind: "runner_error", message: "RSpec execution or JSON report failed: #{e.message}" },
261
+ })
262
+ raise Error, "RSpec did not produce a valid JSON report: #{e.message}"
263
+ end
264
+
265
+ # Flush executions before acknowledging the batch; bktec decides its outcome.
266
+ flush_collector
267
+ @client.request("POST", path, { status: "completed", report_format: "rspec-json", report: native_report })
268
+ end
269
+ end
270
+
271
+ # Replaces BATCH_PLACEHOLDER in a formatter output path with the batch ID,
272
+ # or prefixes the file name with it when the path has no placeholder.
273
+ # Streams and devices such as /dev/stdout are left unchanged.
274
+ def batch_output_path(path, id)
275
+ return path if File.exist?(path) && !File.file?(path)
276
+ return path.gsub(BATCH_PLACEHOLDER, id) if path.include?(BATCH_PLACEHOLDER)
277
+
278
+ path.sub(%r{[^/]*\z}) { |file| "#{id}-#{file}" }
279
+ end
280
+
281
+ def reset_batch
282
+ # Finish the previous collector session before clearing its execution records.
283
+ flush_collector
284
+ Buildkite::TestCollector.session = nil
285
+ Buildkite::TestCollector::Uploader.traces.clear
286
+
287
+ # Keep application configuration/hooks, but discard the previous batch's state.
288
+ RSpec.clear_examples
289
+ RSpec.world.wants_to_quit = !!@stopping
290
+ RSpec.world.non_example_failure = false
291
+ # RSpec 3.10 has no separate rspec_is_quitting flag.
292
+ RSpec.world.rspec_is_quitting = false if RSpec.world.respond_to?(:rspec_is_quitting=)
293
+ end
294
+
295
+ def flush_collector
296
+ Buildkite::TestCollector.session&.send_remaining_data
297
+ Buildkite::TestCollector.session&.close
298
+ Buildkite::TestCollector::OTel.force_flush
299
+ end
300
+ end
301
+ end
@@ -5,6 +5,7 @@ require "rspec/expectations"
5
5
 
6
6
  require_relative "../rspec_plugin/reporter"
7
7
  require_relative "../rspec_plugin/trace"
8
+ require_relative "../rspec_plugin/phase_spans"
8
9
 
9
10
  Buildkite::TestCollector.uploader = Buildkite::TestCollector::Uploader
10
11
 
@@ -9,6 +9,7 @@ module Buildkite
9
9
  @context_key = context_key
10
10
  @span_filter = span_filter && SpanFilter.new(span_filter)
11
11
  @spans = {}
12
+ @populated_phases = {}
12
13
  @mutex = Mutex.new
13
14
  @active = true
14
15
  end
@@ -18,8 +19,14 @@ module Buildkite
18
19
  return unless test_span_trace_id
19
20
  return unless test_span_trace_id == span.context.trace_id
20
21
 
22
+ parent = OpenTelemetry::Trace.current_span(parent_context)
21
23
  @mutex.synchronize do
22
- @spans[span] = true if @active
24
+ next unless @active
25
+
26
+ @spans[span] = true
27
+ # A child that starts after its phase finished (async work from a
28
+ # hook) must not re-add the phase, or it would live until shutdown.
29
+ @populated_phases[parent] = true if @spans.key?(parent) && phase_span?(parent)
23
30
  end
24
31
  rescue Exception => e # rubocop:disable Lint/RescueException
25
32
  ExceptionHandling.reraise_fatal(e)
@@ -34,13 +41,14 @@ module Buildkite
34
41
  def on_finish(span)
35
42
  unless @span_filter
36
43
  @mutex.synchronize do
37
- @processor.on_finish(span) if @active && @spans.delete(span)
44
+ @processor.on_finish(span) if @active && accept(span)
38
45
  end
39
46
  return
40
47
  end
41
48
 
42
- return unless @mutex.synchronize { @active && @spans.delete(span) }
43
- return unless @span_filter.retain?(span)
49
+ return unless @mutex.synchronize { @active && accept(span) }
50
+ # Phase spans are structure the UI relies on; the filter never sees them.
51
+ return unless phase_span?(span) || @span_filter.retain?(span)
44
52
 
45
53
  @mutex.synchronize do
46
54
  @processor.on_finish(span) if @active
@@ -65,12 +73,28 @@ module Buildkite
65
73
  @mutex.synchronize do
66
74
  @active = false
67
75
  @spans.clear
76
+ @populated_phases.clear
68
77
  end
69
78
  success
70
79
  end
71
80
 
72
81
  private
73
82
 
83
+ # Called under @mutex. A phase span that grouped nothing and did not
84
+ # fail says nothing the test span does not, so an uninstrumented
85
+ # suite exports no child spans at all.
86
+ def accept(span)
87
+ return false unless @spans.delete(span)
88
+ return true unless phase_span?(span)
89
+
90
+ @populated_phases.delete(span) || span.status.code != OpenTelemetry::Trace::Status::UNSET
91
+ end
92
+
93
+ # Only called with tracked spans, which have a name.
94
+ def phase_span?(span)
95
+ PHASE_SPAN_NAMES.value?(span.name)
96
+ end
97
+
74
98
  def success
75
99
  OpenTelemetry::SDK::Trace::Export::SUCCESS
76
100
  end
@@ -9,6 +9,7 @@ module Buildkite::TestCollector
9
9
 
10
10
  # Accepted by the Buildkite OTLP traces receiver for its run-key header
11
11
  # (Analytics::API::TracesController::RUN_KEY_FORMAT); keep them in sync.
12
+ RUN_KEY_HEADER = "Buildkite-Tests-Run-Key"
12
13
  RUN_KEY_FORMAT = /\A[!-~]{1,255}\z/
13
14
 
14
15
  EXECUTION_VIA_ATTRIBUTE = "buildkite.execution.via"
@@ -28,6 +29,23 @@ module Buildkite::TestCollector
28
29
 
29
30
  TEST_SPAN_NAME = "test.execution"
30
31
 
32
+ # Names each OTLP request's stream so the receiver can refuse child spans
33
+ # without decoding the body. The collector defines these values; a
34
+ # receiver should treat a request without the header as "test", because
35
+ # older collectors send none.
36
+ SPAN_STREAM_HEADER = "Buildkite-Tests-Span-Stream"
37
+ TEST_SPAN_STREAM = "test"
38
+ CHILD_SPAN_STREAM = "child"
39
+
40
+ # Direct children of the test span that group instrumented child spans by
41
+ # when they happened. Fixed names so every collector can emit the same
42
+ # three and the UI can expand one level and stop.
43
+ PHASE_SPAN_NAMES = {
44
+ setup: "test.setup",
45
+ body: "test.body",
46
+ teardown: "test.teardown",
47
+ }.freeze
48
+
31
49
  # Passed explicitly to both batch processors so the process-wide OTEL_BSP_*
32
50
  # settings do not affect Buildkite export. SDK defaults unless noted.
33
51
  EXPORT_TIMEOUT_MILLISECONDS = 30_000
@@ -51,6 +69,9 @@ module Buildkite::TestCollector
51
69
  TEST_SPAN_ATTRIBUTE_LENGTH_LIMIT = 10_243
52
70
  TEST_SPAN_EVENT_ATTRIBUTE_LENGTH_LIMIT = 16_384
53
71
  TEST_SPAN_EVENT_COUNT_LIMIT = 100
72
+ # The SDK default, pinned so OTEL_*_ATTRIBUTE_COUNT_LIMIT cannot strip
73
+ # execution identity, results, or failure details from test spans.
74
+ TEST_SPAN_ATTRIBUTE_COUNT_LIMIT = 128
54
75
  # Mirrors TestResult.FAILURE_REASON_MAX_LENGTH in ta-ingestion.
55
76
  FAILURE_REASON_MAX_LENGTH = 1_024
56
77
  # Keep in sync with TestResult.FAILURE_EXPANDED_MAX_LENGTH (10,240) in
@@ -179,7 +200,6 @@ module Buildkite::TestCollector
179
200
 
180
201
  @api_token = api_token
181
202
  @run_key = run_env["key"]
182
- headers = request_headers(run_env, api_token)
183
203
 
184
204
  # Resources identify the entities that produced the telemetry. Details
185
205
  # about the Test Engine run and test framework describe each execution
@@ -187,9 +207,11 @@ module Buildkite::TestCollector
187
207
  resource = producer_resource(run_env)
188
208
  @run_attributes = run_attributes(run_env, tags)
189
209
 
190
- @test_span_provider = build_test_span_provider(endpoint, headers, resource)
210
+ test_headers = request_headers(run_env, api_token, stream: TEST_SPAN_STREAM)
211
+ child_headers = request_headers(run_env, api_token, stream: CHILD_SPAN_STREAM)
212
+ @test_span_provider = build_test_span_provider(endpoint, test_headers, resource)
191
213
  @tracer = @test_span_provider.tracer(TRACER_NAME, Buildkite::TestCollector::VERSION)
192
- configure_child_export(endpoint, headers, resource, span_filter: span_filter)
214
+ configure_child_export(endpoint, child_headers, resource, span_filter: span_filter)
193
215
  register_shutdown_at_exit
194
216
  rescue Exception => e # rubocop:disable Lint/RescueException
195
217
  ExceptionHandling.reraise_fatal(e)
@@ -233,11 +255,79 @@ module Buildkite::TestCollector
233
255
  def with_test_span(span)
234
256
  return yield unless span
235
257
 
236
- OpenTelemetry::Context.with_value(test_span_context_key, span.context.trace_id) do
258
+ OpenTelemetry::Context.with_values(test_span_context_key => span.context.trace_id, test_span_key => span) do
237
259
  OpenTelemetry::Trace.with_span(span) { yield }
238
260
  end
239
261
  end
240
262
 
263
+ # The test span of the example running in this fiber, or nil outside
264
+ # one. Read from context rather than the current span, because an
265
+ # around hook's instrumentation may have made its own span current.
266
+ def current_test_span
267
+ return unless enabled?
268
+
269
+ span = OpenTelemetry::Context.current.value(test_span_key)
270
+ span if span&.recording?
271
+ rescue Exception => e # rubocop:disable Lint/RescueException
272
+ ExceptionHandling.reraise_fatal(e)
273
+ warn "[buildkite-test_collector] Could not read the current OpenTelemetry test span: #{e.class}: #{e.message}"
274
+ nil
275
+ end
276
+
277
+ # Phase spans come from the global provider, like the instrumentation
278
+ # spans they group, so they reach the child span exporter (or a
279
+ # suite-owned provider's). The parent is the test span itself, not the
280
+ # current span: an around hook's open span must not capture a phase.
281
+ # VERSION resolves lexically, so a suite that stub_consts
282
+ # Buildkite::TestCollector during an example does not break it.
283
+ def start_phase_span(phase, test_span)
284
+ tracer = OpenTelemetry.tracer_provider.tracer(TRACER_NAME, VERSION)
285
+ tracer.start_span(
286
+ PHASE_SPAN_NAMES.fetch(phase),
287
+ with_parent: OpenTelemetry::Trace.context_with_span(test_span),
288
+ kind: :internal,
289
+ )
290
+ rescue Exception => e # rubocop:disable Lint/RescueException
291
+ ExceptionHandling.reraise_fatal(e)
292
+ warn "[buildkite-test_collector] Could not start OpenTelemetry #{phase} span: #{e.class}: #{e.message}"
293
+ nil
294
+ end
295
+
296
+ # Makes the span current until detach_span is called with the returned token.
297
+ def attach_span(span)
298
+ return unless span
299
+
300
+ OpenTelemetry::Context.attach(OpenTelemetry::Trace.context_with_span(span))
301
+ rescue Exception => e # rubocop:disable Lint/RescueException
302
+ ExceptionHandling.reraise_fatal(e)
303
+ warn "[buildkite-test_collector] Could not make OpenTelemetry span current: #{e.class}: #{e.message}"
304
+ nil
305
+ end
306
+
307
+ def detach_span(token)
308
+ return unless token
309
+
310
+ OpenTelemetry::Context.detach(token)
311
+ rescue Exception => e # rubocop:disable Lint/RescueException
312
+ ExceptionHandling.reraise_fatal(e)
313
+ warn "[buildkite-test_collector] Could not restore the OpenTelemetry context: #{e.class}: #{e.message}"
314
+ end
315
+
316
+ # Each failure becomes an exception event, and the last one the span's
317
+ # status; several after hooks can fail in one teardown phase.
318
+ def finish_phase_span(span, failures)
319
+ return unless span
320
+
321
+ failures.each { |failure| span.record_exception(failure) }
322
+ if (last = failures.last)
323
+ span.status = OpenTelemetry::Trace::Status.error(last.message.to_s[0, FAILURE_REASON_MAX_LENGTH])
324
+ end
325
+ span.finish
326
+ rescue Exception => e # rubocop:disable Lint/RescueException
327
+ ExceptionHandling.reraise_fatal(e)
328
+ warn "[buildkite-test_collector] Could not finish OpenTelemetry phase span: #{e.class}: #{e.message}"
329
+ end
330
+
241
331
  # "Now" as the SDK would stamp it: the realtime clock, in seconds.
242
332
  # Not Time.now, which suites that freeze time (Timecop) fake out.
243
333
  def current_timestamp
@@ -257,14 +347,12 @@ module Buildkite::TestCollector
257
347
  warn "[buildkite-test_collector] Could not finish OpenTelemetry test span: #{e.class}: #{e.message}"
258
348
  end
259
349
 
260
- # Records a point-in-time annotation as an event on whichever span is
261
- # current, which during a test is the test's own trace. Safe to call
262
- # when export is off or nothing is recording: it just does nothing.
350
+ # Records a point-in-time annotation as an event on the test span, not
351
+ # the current span, which during the example is the test.body phase.
352
+ # Does nothing outside an example or when export is off.
263
353
  def annotate(content)
264
- return unless enabled?
265
-
266
- span = OpenTelemetry::Trace.current_span
267
- return unless span.recording?
354
+ span = current_test_span
355
+ return unless span
268
356
 
269
357
  span.add_event("test.annotation", attributes: { "buildkite.annotation" => content.to_s })
270
358
  rescue Exception => e # rubocop:disable Lint/RescueException
@@ -360,10 +448,12 @@ module Buildkite::TestCollector
360
448
  id_generator: SecureRandomIdGenerator,
361
449
  resource: resource,
362
450
  # Lengths are characters, not bytes. Explicit so the process-wide
363
- # OTEL_SPAN_*/OTEL_EVENT_* length and event count limits do not apply
364
- # to test spans; the other count limits keep SDK defaults.
451
+ # OTEL_SPAN_*/OTEL_EVENT_* settings do not apply to test spans; link
452
+ # limits keep SDK defaults.
365
453
  span_limits: OpenTelemetry::SDK::Trace::SpanLimits.new(
454
+ attribute_count_limit: TEST_SPAN_ATTRIBUTE_COUNT_LIMIT,
366
455
  attribute_length_limit: TEST_SPAN_ATTRIBUTE_LENGTH_LIMIT,
456
+ event_attribute_count_limit: TEST_SPAN_ATTRIBUTE_COUNT_LIMIT,
367
457
  event_attribute_length_limit: TEST_SPAN_EVENT_ATTRIBUTE_LENGTH_LIMIT,
368
458
  event_count_limit: TEST_SPAN_EVENT_COUNT_LIMIT,
369
459
  ),
@@ -563,6 +653,10 @@ module Buildkite::TestCollector
563
653
  @test_span_context_key ||= OpenTelemetry::Context.create_key("buildkite.test.execution")
564
654
  end
565
655
 
656
+ def test_span_key
657
+ @test_span_key ||= OpenTelemetry::Context.create_key("buildkite.test.execution.span")
658
+ end
659
+
566
660
  # User tags travel under the buildkite.tag. prefix, which the server
567
661
  # strips and turns into upload-level tags.
568
662
  def tag_attributes(tags)
@@ -779,8 +873,11 @@ module Buildkite::TestCollector
779
873
  []
780
874
  end
781
875
 
782
- def request_headers(run_env, api_token)
783
- headers = { "Buildkite-Tests-Run-Key" => run_env["key"] }
876
+ def request_headers(run_env, api_token, stream:)
877
+ headers = {
878
+ RUN_KEY_HEADER => run_env["key"],
879
+ SPAN_STREAM_HEADER => stream,
880
+ }
784
881
  headers["Authorization"] = authorization_header(api_token) if api_token
785
882
  headers
786
883
  end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Buildkite::TestCollector::RSpecPlugin
4
+ # Splits each test.execution span into three phase spans: test.setup
5
+ # (before hooks and let!), test.body (the example block), and test.teardown
6
+ # (after hooks and mock verification). Each phase span is current while its
7
+ # phase runs, so instrumentation spans nest under the phase they ran in.
8
+ #
9
+ # RSpec::Core::Example#run calls run_before_example, then the example block,
10
+ # then run_after_example in an ensure; these private methods are the
11
+ # narrowest wrap points that see the failures each phase raises. Around
12
+ # hooks run outside all three, so their own spans stay direct children of
13
+ # the test span alongside the phases.
14
+ module PhaseSpans
15
+ # Bound at load so a suite that stub_consts Buildkite::TestCollector in a
16
+ # before hook still reaches the real module from run_after_example. Every
17
+ # OTel method called here rescues its own errors, so nothing in this
18
+ # module can raise ahead of RSpec's teardown.
19
+ OTel = Buildkite::TestCollector::OTel
20
+
21
+ private
22
+
23
+ def run_before_example
24
+ test_span = OTel.current_test_span
25
+ return super unless test_span
26
+
27
+ buildkite_phase(:setup, test_span) { super() }
28
+
29
+ # Left current until run_after_example, which runs even when the
30
+ # example block raises.
31
+ @buildkite_body_span = OTel.start_phase_span(:body, test_span)
32
+ @buildkite_body_token = OTel.attach_span(@buildkite_body_span)
33
+ end
34
+
35
+ def run_after_example
36
+ buildkite_finish_body_span
37
+ test_span = OTel.current_test_span
38
+ return super unless test_span
39
+
40
+ buildkite_phase(:teardown, test_span) do |failures|
41
+ failures_before = buildkite_failures
42
+ super()
43
+ failures.concat(buildkite_failures - failures_before)
44
+ end
45
+ end
46
+
47
+ # Anything the block raises is the phase's failure; a block that observes
48
+ # failures without raising appends them to the yielded list.
49
+ def buildkite_phase(phase, test_span)
50
+ failures = []
51
+ span = OTel.start_phase_span(phase, test_span)
52
+ token = OTel.attach_span(span)
53
+ yield failures
54
+ rescue Exception => e # rubocop:disable Lint/RescueException
55
+ # `skip` in a before hook ends the example early; RSpec reports that as
56
+ # pending, not as a failure.
57
+ failures << e unless e.is_a?(RSpec::Core::Pending::SkipDeclaredInExample)
58
+ raise
59
+ ensure
60
+ OTel.detach_span(token)
61
+ OTel.finish_phase_span(span, failures)
62
+ end
63
+
64
+ def buildkite_finish_body_span
65
+ OTel.detach_span(@buildkite_body_token)
66
+ OTel.finish_phase_span(@buildkite_body_span, buildkite_failures)
67
+ ensure
68
+ @buildkite_body_span = nil
69
+ @buildkite_body_token = nil
70
+ end
71
+
72
+ # After hooks and mock verification add their failures to the example
73
+ # rather than raising: the first replaces nil, a second wraps both in a
74
+ # MultipleExceptionError, and later ones are added to that same object.
75
+ def buildkite_failures
76
+ case exception
77
+ when nil then []
78
+ when RSpec::Core::MultipleExceptionError then exception.all_exceptions.dup
79
+ else [exception]
80
+ end
81
+ end
82
+ end
83
+ end
84
+
85
+ RSpec::Core::Example.prepend(Buildkite::TestCollector::RSpecPlugin::PhaseSpans)
@@ -14,6 +14,19 @@ module Buildkite::TestCollector::RSpecPlugin
14
14
  def handle_example(notification)
15
15
  example = notification.example
16
16
  trace = Buildkite::TestCollector.uploader.traces[example.id]
17
+ # A failing before(:context) or an outer around hook that raises first
18
+ # fails the example without entering our around(:each). The span is the
19
+ # submission in OTLP mode, so start one now; it times the reporting
20
+ # only, since the example never ran.
21
+ if trace.nil? && Buildkite::TestCollector.otel_enabled? && example.execution_result.status == :failed
22
+ trace = Buildkite::TestCollector::RSpecPlugin::Trace.new(
23
+ example,
24
+ history: {},
25
+ location_prefix: Buildkite::TestCollector.location_prefix,
26
+ external_id: Buildkite::TestCollector::UUID.v7,
27
+ )
28
+ trace.otel_span = Buildkite::TestCollector::OTel.start_test_span(test: trace)
29
+ end
17
30
  return unless trace
18
31
 
19
32
  trace.example = example
@@ -2,7 +2,7 @@
2
2
 
3
3
  module Buildkite
4
4
  module TestCollector
5
- VERSION = "2.16.0"
5
+ VERSION = "2.17.0"
6
6
  NAME = "buildkite-test_collector"
7
7
  end
8
8
  end
metadata CHANGED
@@ -1,11 +1,11 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: buildkite-test_collector
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.16.0
4
+ version: 2.17.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Buildkite
8
- bindir: bin
8
+ bindir: exe
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
@@ -109,7 +109,8 @@ dependencies:
109
109
  version: '0'
110
110
  email:
111
111
  - support+analytics@buildkite.com
112
- executables: []
112
+ executables:
113
+ - buildkite-rspec
113
114
  extensions: []
114
115
  extra_rdoc_files: []
115
116
  files:
@@ -132,6 +133,8 @@ files:
132
133
  - buildkite.yaml
133
134
  - cucumber.yml
134
135
  - docs/opentelemetry.md
136
+ - exe/buildkite-rspec
137
+ - lib/buildkite/rspec_runner.rb
135
138
  - lib/buildkite/test_collector.rb
136
139
  - lib/buildkite/test_collector/ci.rb
137
140
  - lib/buildkite/test_collector/cucumber_plugin/trace.rb
@@ -151,6 +154,7 @@ files:
151
154
  - lib/buildkite/test_collector/otel/span_filter.rb
152
155
  - lib/buildkite/test_collector/otel/span_metrics_reporter.rb
153
156
  - lib/buildkite/test_collector/otel/test_span_metrics_reporter.rb
157
+ - lib/buildkite/test_collector/rspec_plugin/phase_spans.rb
154
158
  - lib/buildkite/test_collector/rspec_plugin/reporter.rb
155
159
  - lib/buildkite/test_collector/rspec_plugin/trace.rb
156
160
  - lib/buildkite/test_collector/session.rb