koderift-rails 2.1.2 → 2.2.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: 9e0939c31d9ed90e327052741d51a200a559c6723a06a282cc9df8c44c3585e9
4
- data.tar.gz: 78ec3fd6c4cb9202fd51ca6443ef2c777e222bb1fd3bf543187a03c7341945ea
3
+ metadata.gz: 5e6d13c9f0576fdaaf7f88a3453b3b2afabed986844f83063780af1eaabde34f
4
+ data.tar.gz: ab074ec0373e10dd00f73ec16aafaafac1d496f1b8aed0c987553d0daee178d9
5
5
  SHA512:
6
- metadata.gz: 02e615e243fecb096cb7b81246b52eb0915ff983f7d35e4b741979e1008136746c51e15e01042f4f4b9728a4980c4d2c87774f555d19b97873ac6a4dfe7b3327
7
- data.tar.gz: 81f126d9398acba954df8fa2260c2ce3a3dadc013139d8cee0d07958f9151b553b5da3a76549b1e60d2e0145cd2669d0d59d039a1db3bc6d2c5339114a84bea0
6
+ metadata.gz: 8873a62cff6a6eff80b048d8b17c053b7ab6b805388a8a2323f3ed6ef8fdc75ce413e95680d3a1688abfeaecc31bfa63dc88b7ab7659fd89aea4152ea8e0ec1f
7
+ data.tar.gz: c540640a772614a79f9b916741356b7c14a6bf71c08824036879e6fa8e10052abad7c1df34f7d007976bc5af8936930f2a7415bde8026b63466f7be617382b5f
data/CHANGELOG.md CHANGED
@@ -6,6 +6,113 @@ This project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
  Releases before 1.3.4 were installed from git and were never published to
7
7
  RubyGems; they are listed for continuity.
8
8
 
9
+ ## [2.2.0] - 2026-11-22
10
+
11
+ Distributed tracing with W3C Trace Context. Traces now link with OpenTelemetry,
12
+ Sentry and browsers, spans nest, and a request's trace continues into the
13
+ Sidekiq jobs it enqueues.
14
+
15
+ ### Added
16
+ - Incoming requests continue a trace from `X-Koderift-Traceparent`, then a W3C
17
+ `traceparent`, then Sentry's `sentry-trace`, then the older
18
+ `X-Koderift-Trace-ID`. A Koderift trace ID wins whenever it disagrees with
19
+ `traceparent` or `sentry-trace`, because nothing else sets it. With none of
20
+ them a request starts a new trace. A malformed header is ignored.
21
+ - Outbound Net::HTTP calls send `traceparent`, naming the call's own span as the
22
+ parent, and any `tracestate` that arrived with the trace. A call that is not
23
+ recorded (to a loopback or ignored host, or made outside a request, job or
24
+ transaction) names the span around it instead. They also send the
25
+ same context in the gem's own `X-Koderift-Traceparent` header. A `traceparent`
26
+ already on the request (set by OpenTelemetry, Datadog, New Relic, a Sentry SDK
27
+ or your code) is never overwritten. Those tools rewrite `traceparent` but not
28
+ the Koderift header, so a Koderift app downstream still nests under the exact
29
+ call. `X-Koderift-Trace-ID` is still sent, now with the 32-hex trace ID, for
30
+ apps on older versions.
31
+ - Sidekiq client middleware. A job enqueued inside a request, job or
32
+ transaction carries its trace (`koderift_traceparent`, plus
33
+ `koderift_trace_id` for servers on older versions). The job's line shares the
34
+ request's trace ID and names the enqueuing span as its parent. This covers
35
+ `perform_async`, `perform_in`, bulk pushes and ActiveJob on the Sidekiq
36
+ adapter. A job that already carries a trace keeps it, so retries and
37
+ scheduled jobs stay in the trace they were enqueued in.
38
+ - Every span has a `span_id` and a `start_ms` (milliseconds from the start of
39
+ its request, job or transaction). `start_ms` is left out in the rare case a
40
+ start time cannot be placed inside its unit. Spans inside a `with_child_span` block also
41
+ have a `parent_span_id`. A span without one belongs to the line's root span.
42
+ - Request, job and transaction lines gain `span_id` (their root span),
43
+ `parent_span_id` (the caller's span, when the trace came from one) and
44
+ `started_at` (UTC ISO-8601 with milliseconds). Manual captures gain `span_id`.
45
+ - A transaction started inside a request or job joins its trace, as a child of
46
+ the span open there. Starting a transaction while another one is open on the
47
+ same thread still finishes the open one first, as in 2.1.
48
+
49
+ ### Changed
50
+ - Trace IDs are W3C trace IDs, 32 lowercase hex characters, instead of UUIDs. A
51
+ UUID in `X-Koderift-Trace-ID` or a job's `koderift_trace_id` is still
52
+ accepted and normalised (dashes removed, lowercased). A value there that is
53
+ not a UUID is now ignored and a new trace starts; before, any string was used
54
+ as it was.
55
+ - Three specs that asserted the UUID format now assert the 32-hex format.
56
+
57
+ ### Fixed
58
+ - Each request and job recorded the SQL queries, partial renders and Searchkick
59
+ searches of every other request and job running at the same time in the
60
+ process (multi-threaded Puma, Sidekiq). ActiveSupport::Notifications
61
+ subscribers are process-wide, and the gem's were not limited to their own
62
+ thread. Each unit now records only its own. Per-request query counts may drop
63
+ slightly after you upgrade, because other threads' queries are no longer
64
+ included. Queries a request runs on threads or fibers it starts itself
65
+ (Concurrent::Promises, Parallel, `Enumerator#next`, Async tasks) are no
66
+ longer counted either; `load_async` queries still are.
67
+ - A transaction started inside a request no longer stops the request recording
68
+ HTTP calls, custom spans and manual breadcrumbs once it finishes. Its queries
69
+ now appear on the transaction's line only, not on both lines.
70
+ - A non-block transaction left unfinished can no longer leak into a later
71
+ request on the same thread. Before, finishing it there restored the earlier
72
+ request's trace ID and capture context, so later manual captures carried the
73
+ earlier request's ID and user. The abandoned transaction's own line, written
74
+ when the next transaction starts, still picks up that later request's path,
75
+ method, user and tags, as in 2.1.
76
+ - A job run with `perform_inline` inside another job no longer clears that
77
+ job's trace and capture context. Its Koderift scope (tags and user set with
78
+ `set_tag` and `set_user`) is still reset, as before.
79
+ - An exception inside one of the gem's notification callbacks can no longer
80
+ fail the query or render being instrumented.
81
+ - On Rails 7.1.0-7.1.3, `load_async` queries reported durations 1000 times too
82
+ long.
83
+
84
+ ### Notes
85
+ - No configuration needed.
86
+ - Older Koderift app and agent versions ignore the new keys until the Koderift
87
+ app update that uses them. Services on older gem versions store UUID trace IDs
88
+ with dashes and 2.2.0 stores 32 hex, so traces across mixed versions link once
89
+ that update normalises stored trace IDs.
90
+ - A caller on an older gem version that also runs Sentry, OpenTelemetry,
91
+ Datadog or New Relic sends that tool's trace header next to its Koderift
92
+ trace ID. A 2.2 service follows the Koderift trace ID, so the trace still
93
+ links, but the older header carries no parent span, so those requests sit
94
+ under the trace's root until the caller upgrades.
95
+ - A job that enqueues itself (for example with `perform_in` at the end of
96
+ `perform`) stays in the trace it started in, so a self-scheduling job builds
97
+ one ever-growing trace.
98
+ - Span-heavy requests grow slightly in logged bytes: each span gains about 45
99
+ bytes (`span_id`, `start_ms`), and a span nested in a `with_child_span` block
100
+ about 35 more (`parent_span_id`).
101
+ - A Sentry browser SDK keeps one trace ID for a whole page, so every request a
102
+ page makes now shares a trace ID and they appear together in Koderift's
103
+ cross-service trace view.
104
+ - New traces are sent as sampled (`01`), and a `sentry-trace` without a sampled
105
+ flag is read as sampled. A downstream service using OpenTelemetry's
106
+ parent-based sampler therefore records the calls it receives from your app.
107
+ - Only Net::HTTP, and clients built on it such as Faraday's default adapter,
108
+ sends trace headers. They go to every host your app calls, including
109
+ third-party APIs. Trace and span IDs are random, but an incoming `tracestate`
110
+ is passed on as received.
111
+ - A call that raises (a timeout, a refused connection) records no span, so the
112
+ service it reached may name a parent span that is not in your trace.
113
+ - On Rails 7.2, an ActiveJob enqueued inside a database transaction is pushed
114
+ when the transaction commits, so its parent is the span open at commit.
115
+
9
116
  ## [2.1.2] - 2026-11-19
10
117
 
11
118
  Fixes missing request detail for controllers that inherit from
data/README.md CHANGED
@@ -72,6 +72,7 @@ the agent's `agent.yml`. See the [changelog](CHANGELOG.md).
72
72
  * DB runtime, view runtime, allocations
73
73
  * Current user ID
74
74
  * Request ID, IP address, user agent, referer
75
+ * Trace ID, span IDs and start offsets (see [Distributed tracing](#distributed-tracing))
75
76
  * Request params (filtered — passwords, tokens etc removed)
76
77
  * Top 5 slowest partials with render times
77
78
  * Top 5 slowest SQL queries
@@ -79,6 +80,62 @@ the agent's `agent.yml`. See the [changelog](CHANGELOG.md).
79
80
  * Exception class, message, and cause chain
80
81
  * Stack traces (requires `keep_original_rails_log: true`)
81
82
 
83
+ ## Distributed tracing
84
+
85
+ The gem continues a trace that reaches your app and passes it on. There is
86
+ nothing to configure.
87
+
88
+ Incoming requests continue the first usable trace header, in this order:
89
+
90
+ 1. `X-Koderift-Traceparent`: the gem's own copy, sent by another app running
91
+ koderift-rails 2.2 or later
92
+ 2. `traceparent`: W3C Trace Context, sent by OpenTelemetry, recent Sentry SDKs
93
+ and other tracing tools
94
+ 3. `sentry-trace`: sent by Sentry SDKs, including the browser SDK
95
+ 4. `X-Koderift-Trace-ID`: sent by koderift-rails before 2.2 (a UUID)
96
+
97
+ A Koderift trace ID wins whenever it disagrees with `traceparent` or
98
+ `sentry-trace`, because nothing else sets it. That keeps a caller on an older
99
+ version linked when it also runs Sentry or an APM; its requests sit under the
100
+ trace's root, since the older header carries no parent span. With none of the
101
+ headers, the request starts a new trace. A malformed header is ignored.
102
+
103
+ Outbound Net::HTTP calls carry the trace on:
104
+
105
+ * `traceparent` names the call's own span as the parent (or the span around the
106
+ call, when the call itself is not recorded), and any `tracestate` that came in
107
+ with the trace goes with it. If the request already has a
108
+ `traceparent`, set by OpenTelemetry, Datadog, New Relic, a Sentry SDK or your
109
+ own code, the gem leaves it alone, so it works alongside those tools.
110
+ * `X-Koderift-Traceparent` carries the same context in a header those tools
111
+ don't touch. When one of them rewrites `traceparent`, a Koderift app
112
+ downstream still nests under the exact call that reached it, which is why
113
+ this header comes first above.
114
+ * `X-Koderift-Trace-ID` carries the trace ID alone, for apps on older versions.
115
+
116
+ Only Net::HTTP, and clients built on it such as Faraday's default adapter,
117
+ sends these headers. They go to every host your app calls, including
118
+ third-party APIs; trace and span IDs are random, but an incoming `tracestate` is
119
+ passed on as received.
120
+
121
+ Sidekiq jobs enqueued inside a request, job or transaction carry its trace.
122
+ The job's line shares the trace ID and names the span that enqueued it as its
123
+ parent. That includes `perform_in` (the trace is stored when the job is
124
+ scheduled), bulk pushes and ActiveJob on the Sidekiq adapter. A job that
125
+ already carries a trace keeps it, so a retry stays in its original trace. On
126
+ Rails 7.2, an ActiveJob enqueued inside a database transaction is pushed at
127
+ commit, so its parent is the span open then. A job that enqueues itself stays in
128
+ the trace it started in.
129
+
130
+ In the log lines, every request, job and transaction line has a `trace_id`
131
+ (32 hex), its own `span_id`, a `started_at` time, and a `parent_span_id` when
132
+ the trace came from a caller. Every span has a `span_id` and, unless its start
133
+ cannot be placed inside the unit, a `start_ms` offset; a span inside a
134
+ `with_child_span` block names that block as its `parent_span_id`.
135
+
136
+ New traces are marked sampled, so a downstream service using OpenTelemetry's
137
+ parent-based sampler records the calls your app makes to it.
138
+
82
139
  ## Reporting handled errors
83
140
 
84
141
  Automatic instrumentation only sees what reaches Rails: a request, a Sidekiq
@@ -224,7 +281,7 @@ find out at migration time rather than from a silent no-op.
224
281
  | --- | --- |
225
282
  | `capture_check_in` | Cron *monitors* — alerting when a job never runs. Cron errors and slowness are covered (above); detecting an absence needs schedule definitions Koderift does not have yet. |
226
283
  | `close`, `clone_hub_to_current_thread`, `with_session_tracking` | Nothing to do behind them: captures are written synchronously with no in-process buffer, and all state is already thread-local. |
227
- | `get_traceparent`, `get_baggage` | Distributed tracing works, via the `X-Koderift-Trace-ID` header this gem already propagates. |
284
+ | `get_traceparent`, `get_baggage` | Trace context is read and sent automatically (see [Distributed tracing](#distributed-tracing)); there is no call to read it. |
228
285
  | Profiling, release health | Configured inside `Sentry.init` with no call sites, so nothing to replace. Release comparison is on the Koderift deploy-impact view, keyed by the agent's `app_version`. |
229
286
 
230
287
  ## Requirements
@@ -6,6 +6,7 @@ require 'koderift/rails/event'
6
6
  require 'koderift/rails/scope'
7
7
  require 'koderift/rails/breadcrumb'
8
8
  require 'koderift/rails/lograge_config'
9
+ require 'koderift/rails/trace_context'
9
10
 
10
11
  module Koderift
11
12
  module Rails
@@ -189,7 +190,8 @@ module Koderift
189
190
  # sampled: sample_rate is Sentry's ERROR sample rate, and silently
190
191
  # dropping units of work would make the APM view lie about throughput.
191
192
  def transaction(component:, action:, message:, duration_ms:, request_id:,
192
- trace_id:, result:, level: 'info')
193
+ trace_id:, result:, level: 'info', span_id: nil,
194
+ parent_span_id: nil, started_at: nil)
193
195
  return nil unless initialized?
194
196
 
195
197
  allowed, warning = rate_limiter.allow(configuration.max_captures_per_minute)
@@ -211,9 +213,12 @@ module Koderift
211
213
  search_count: result[:search_count]
212
214
  )
213
215
 
214
- payload[:request_id] = request_id
215
- payload[:trace_id] = trace_id
216
- payload[:breadcrumbs] = result[:breadcrumbs] if result[:breadcrumbs]
216
+ payload[:request_id] = request_id
217
+ payload[:trace_id] = trace_id
218
+ payload[:span_id] = span_id
219
+ payload[:parent_span_id] = parent_span_id
220
+ payload[:started_at] = started_at
221
+ payload[:breadcrumbs] = result[:breadcrumbs] if result[:breadcrumbs]
217
222
 
218
223
  emit(payload.compact, normalised)
219
224
  Event.new(event_id: event_id, level: normalised, message: message,
@@ -318,6 +323,7 @@ module Koderift
318
323
  action: presence(action || scope.action || ambient[:action]),
319
324
  request_id: presence(ambient[:request_id]),
320
325
  trace_id: presence(Thread.current[:koderift_trace_id]),
326
+ span_id: presence(TraceContext::Current.current_span_id),
321
327
  user_id: presence(resolve_user_id(user_id, merged_user, ambient)),
322
328
  path: presence(ambient[:path]),
323
329
  http_method: presence(ambient[:http_method]),
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'active_support/concern'
4
- require 'securerandom'
4
+ require 'koderift/rails/trace_context'
5
5
  require 'koderift/rails/instrumentation'
6
6
  require 'koderift/rails/scope'
7
7
 
@@ -17,11 +17,7 @@ module Koderift
17
17
  private
18
18
 
19
19
  def koderift_instrument_request
20
- trace_id = request.headers['X-Koderift-Trace-ID'].presence ||
21
- SecureRandom.uuid
22
-
23
- Thread.current[:koderift_trace_id] = trace_id
24
- request.env['koderift.trace_id'] = trace_id
20
+ started_at_ms = Koderift::Rails::TraceContext.now_ms
25
21
 
26
22
  # Ambient context for manual captures. Koderift.capture_exception can be
27
23
  # called from anywhere below this frame -- a model, a service object, a
@@ -29,7 +25,7 @@ module Koderift
29
25
  # request it happened inside. The controller instance is kept so
30
26
  # config.current_user can be resolved at capture time rather than eagerly
31
27
  # on every request that never captures anything.
32
- Thread.current[:koderift_context] = {
28
+ context = {
33
29
  component: self.class.name,
34
30
  action: action_name,
35
31
  request_id: request.request_id,
@@ -38,7 +34,9 @@ module Koderift
38
34
  controller_instance: self
39
35
  }
40
36
 
41
- result = Koderift::Rails::Instrumentation.capture do
37
+ trace_frame = koderift_start_trace(context, started_at_ms)
38
+
39
+ result = Koderift::Rails::Instrumentation.capture(started_at_ms: started_at_ms) do
42
40
  yield
43
41
  end
44
42
 
@@ -48,14 +46,45 @@ module Koderift
48
46
  request.env['koderift.search_count'] = result[:search_count]
49
47
  request.env['koderift.breadcrumbs'] = result[:breadcrumbs]
50
48
  ensure
51
- Thread.current[:koderift_trace_id] = nil
52
- Thread.current[:koderift_context] = nil
49
+ if trace_frame
50
+ # Clears the trace ID and capture context, and anything a nested
51
+ # transaction left behind.
52
+ Koderift::Rails::TraceContext::Current.pop(trace_frame)
53
+ else
54
+ Thread.current[:koderift_trace_id] = nil
55
+ Thread.current[:koderift_context] = nil
56
+ end
53
57
  # Puma reuses threads across requests. Without this reset a tag set for
54
58
  # one user's request would silently attach to the next request served
55
59
  # by the same thread.
56
60
  Koderift::Rails::Scope.reset!
57
61
  end
58
62
 
63
+ # Continues the caller's trace (see TraceContext.incoming for the header
64
+ # precedence) or starts one. A failure here costs the request its trace,
65
+ # never the request itself.
66
+ def koderift_start_trace(context, started_at_ms)
67
+ incoming = Koderift::Rails::TraceContext.incoming(request.headers)
68
+ frame = Koderift::Rails::TraceContext::Current.push(
69
+ kind: :request,
70
+ trace_id: incoming[:trace_id],
71
+ parent_span_id: incoming[:parent_span_id],
72
+ flags: incoming[:flags],
73
+ tracestate: incoming[:tracestate],
74
+ context: context,
75
+ started_at_ms: started_at_ms
76
+ )
77
+
78
+ request.env['koderift.trace_id'] = frame.trace_id
79
+ request.env['koderift.span_id'] = frame.root_span_id
80
+ request.env['koderift.parent_span_id'] = frame.parent_span_id
81
+ request.env['koderift.started_at'] = frame.started_at
82
+ frame
83
+ rescue StandardError
84
+ Thread.current[:koderift_context] = context
85
+ nil
86
+ end
87
+
59
88
  def append_info_to_payload(payload)
60
89
  super
61
90
  config = Koderift::Rails.configuration
@@ -81,6 +110,9 @@ module Koderift
81
110
  payload[:koderift_user_agent] = request.user_agent
82
111
  payload[:koderift_request_id] = request.request_id
83
112
  payload[:koderift_trace_id] = request.env['koderift.trace_id']
113
+ payload[:koderift_span_id] = request.env['koderift.span_id']
114
+ payload[:koderift_parent_span_id] = request.env['koderift.parent_span_id']
115
+ payload[:koderift_started_at] = request.env['koderift.started_at']
84
116
  payload[:koderift_referer] = request.referer
85
117
  payload[:koderift_params] = filtered_params.to_h
86
118
  payload[:koderift_spans] = request.env['koderift.spans']
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Koderift
4
+ module Rails
5
+ # A per-thread stack of frames for one kind of state, and the thread-local
6
+ # keys that state is published under.
7
+ #
8
+ # Each unit of work (a request, a Sidekiq job, a transaction) pushes a frame
9
+ # when it starts and pops it when it ends. Units nest: a transaction inside a
10
+ # request, a job run with perform_inline inside another job. The rule for
11
+ # popping is what makes nesting safe:
12
+ #
13
+ # * A frame that is no longer on the stack touches nothing. That is an
14
+ # abandoned non-block transaction finished long after the unit it was
15
+ # started in has ended. Restoring its saved state would hand the earlier
16
+ # request's trace and collections to whatever runs now.
17
+ # * Otherwise everything from that frame upward is dropped, so an abandoned
18
+ # transaction started inside the unit goes with it, and the frame below is
19
+ # published again.
20
+ # * When the stack empties, the published keys are cleared, or, for a frame
21
+ # created with restore_outside, set back to what they held before the
22
+ # first frame was pushed. Requests and jobs clear: Puma and Sidekiq reuse
23
+ # threads, and nothing from one unit may reach the next.
24
+ class FrameStack
25
+ # Mixed into frame classes.
26
+ module Member
27
+ attr_accessor :outside
28
+
29
+ def restore_outside?
30
+ @restore_outside ? true : false
31
+ end
32
+ end
33
+
34
+ def initialize(stack_key, published_keys, &values_for)
35
+ @stack_key = stack_key
36
+ @published_keys = published_keys
37
+ @values_for = values_for
38
+ end
39
+
40
+ def push(frame)
41
+ stack = (Thread.current[@stack_key] ||= [])
42
+ frame.outside = @published_keys.map { |key| Thread.current[key] } if stack.empty?
43
+ stack.push(frame)
44
+ publish(@values_for.call(frame))
45
+ frame
46
+ end
47
+
48
+ # Returns true when the frame was found and popped.
49
+ def pop(frame)
50
+ stack = Thread.current[@stack_key]
51
+ return false unless stack
52
+
53
+ index = stack.rindex { |f| f.equal?(frame) }
54
+ return false unless index
55
+
56
+ bottom = stack.first
57
+ stack.slice!(index..-1)
58
+
59
+ if stack.empty?
60
+ Thread.current[@stack_key] = nil
61
+ publish(bottom.restore_outside? ? bottom.outside : nil)
62
+ else
63
+ publish(@values_for.call(stack.last))
64
+ end
65
+ true
66
+ end
67
+
68
+ def include?(frame)
69
+ stack = Thread.current[@stack_key]
70
+ stack ? stack.any? { |f| f.equal?(frame) } : false
71
+ end
72
+
73
+ def top
74
+ stack = Thread.current[@stack_key]
75
+ stack && stack.last
76
+ end
77
+
78
+ def clear!
79
+ Thread.current[@stack_key] = nil
80
+ publish(nil)
81
+ end
82
+
83
+ private
84
+
85
+ def publish(values)
86
+ @published_keys.each_with_index do |key, i|
87
+ Thread.current[key] = values && values[i]
88
+ end
89
+ end
90
+ end
91
+ end
92
+ end