Module: RailsOtelContext::ActiveRecordContext

Defined in:
lib/rails_otel_context/activerecord_context.rb

Overview

Extracts ActiveRecord model name, method, and scope from sql.active_record notifications and scope instrumentation.

Two mechanisms work together:

  1. sql.active_record subscriber — captures model name + AR operation type (e.g., “Transaction Load”) at query time via payload.

  2. Scope tracking — wraps scope-generated methods to store the scope name on the Relation object, then captures it at materialization time via Relation#exec_queries. This handles lazy scopes like Transaction.recent_completed.to_a where the scope method returns before SQL fires.

Defined Under Namespace

Modules: ClassMethodScopeTracking, RelationScopeCapture, ScopeNameTracking Classes: Subscriber

Constant Summary collapse

DB_SLOW_ATTR =
'db.slow'

Class Method Summary collapse

Class Method Details

.app_rootObject



230
231
232
# File 'lib/rails_otel_context/activerecord_context.rb', line 230

def app_root
  @app_root
end

.apply_to_span(span, ctx) ⇒ Object

Applies AR context directly to a span. Used by Subscriber#start to enrich spans created by driver-level OTel instrumentation (Trilogy, PG) before our notification subscriber runs. Also reads code.namespace/code.function already set by CallContextProcessor#on_start so the span_name_formatter has full context.



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/rails_otel_context/activerecord_context.rb', line 292

def apply_to_span(span, ctx)
  return unless span.context.valid?

  span.set_attribute('code.activerecord.model', ctx[:model_name]) if ctx[:model_name]
  span.set_attribute('code.activerecord.method', ctx[:method_name]) if ctx[:method_name]
  span.set_attribute('code.activerecord.scope', ctx[:scope_name]) if ctx[:scope_name]
  span.set_attribute('db.query_count', ctx[:query_count]) if ctx[:query_count]
  span.set_attribute('db.async', true) if ctx[:async]

  formatter = RailsOtelContext.configuration.span_name_formatter
  return unless formatter
  return unless span.respond_to?(:attributes) && span.attributes&.key?('db.system')

  # Dup deferred to here: set_attribute calls above need only the original ctx keys.
  # The formatter may inspect code.namespace/code.function already on the span.
  ar_ctx = ctx.dup
  if span.respond_to?(:attributes)
    ar_ctx[:code_namespace] = span.attributes['code.namespace']
    ar_ctx[:code_function]  = span.attributes['code.function']
  end

  original_name = span.name
  new_name = formatter.call(original_name, ar_ctx)
  return unless new_name && new_name != original_name && span.respond_to?(:name=)

  span.set_attribute('l9.orig.name', original_name)
  span.name = new_name
rescue StandardError
  nil
end

.ar_table_model_mapObject

Lazy table_name → model_name index. Built on first use after all models are loaded (eager_load! in production). In development, call reset_ar_table_model_map! after a code reload to get a fresh index.



397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'lib/rails_otel_context/activerecord_context.rb', line 397

def ar_table_model_map
  @ar_table_model_map ||= begin
    next_map = {}
    if defined?(::ActiveRecord::Base)
      ::ActiveRecord::Base.descendants.each do |m|
        model_name = begin
          m.name
        rescue StandardError
          next
        end
        next unless model_name
        # Skip STI subclasses — they share the parent's table_name.
        # Without this guard, AdminUser < User would overwrite users → User
        # with users → AdminUser in the map, giving wrong model names on
        # SQL-named spans (counter caches, update_all).
        next unless m.base_class == m

        table = begin
          m.table_name
        rescue StandardError
          next
        end
        next unless table

        next_map[table] = model_name
      end
    end
    next_map
  end
end

.clear!Object



238
239
240
241
242
# File 'lib/rails_otel_context/activerecord_context.rb', line 238

def clear!
  Thread.current[THREAD_KEY]          = nil
  Thread.current[SCOPE_THREAD_KEY]    = nil
  Thread.current[PENDING_PREPARE_KEY] = nil
end

.currentObject



234
235
236
# File 'lib/rails_otel_context/activerecord_context.rb', line 234

def current
  Thread.current[THREAD_KEY]
end

.extract_table_after(sql, keyword) ⇒ Object

Extracts a table name from sql starting after keyword. Skips one optional leading quote character (‘ “ ’), reads word chars until the next delimiter (space, quote, comma). Returns nil when keyword not found. Saves 1 alloc vs regex: index()+slice allocates only the result String.



378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/rails_otel_context/activerecord_context.rb', line 378

def extract_table_after(sql, keyword)
  idx = sql.index(keyword)
  return nil unless idx

  start = idx + keyword.length
  first = sql.getbyte(start)
  start += 1 if first == BYTE_BACKTICK || first == BYTE_DQUOTE || first == BYTE_SQUOTE # rubocop:disable Style/MultipleComparison

  stop = start
  stop += 1 while stop < sql.length &&
                  (b = sql.getbyte(stop)) != BYTE_SPACE &&
                  b != BYTE_BACKTICK && b != BYTE_DQUOTE && b != BYTE_SQUOTE && b != BYTE_COMMA

  stop > start ? sql[start, stop - start] : nil
end

.install!(app_root: nil) ⇒ Object



218
219
220
221
222
223
224
225
226
227
228
# File 'lib/rails_otel_context/activerecord_context.rb', line 218

def install!(app_root: nil)
  @app_root = File.expand_path(app_root.to_s) if app_root

  return unless defined?(::ActiveSupport::Notifications)
  return unless defined?(::ActiveRecord::Base)

  ActiveSupport::Notifications.subscribe('sql.active_record', Subscriber.new)
  ::ActiveRecord::Base.extend(ScopeNameTracking)
  ::ActiveRecord::Base.extend(ClassMethodScopeTracking)
  ::ActiveRecord::Relation.prepend(RelationScopeCapture)
end

.parse_ar_name(name) ⇒ Object

Parses “Transaction Load” → { model_name: “Transaction”, method_name: “Load” } Uses index+byteslice instead of split to avoid allocating the intermediate Array and two String copies — saves 1 alloc (Array) vs split which returns Array+Strings but with frozen_string_literal the slice shares storage on MRI 3.2+.



327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/rails_otel_context/activerecord_context.rb', line 327

def parse_ar_name(name)
  return nil unless name

  idx = name.index(' ')
  return nil unless idx

  model_name  = name[0, idx]
  method_name = name[idx + 1, name.length]

  return nil if model_name == 'ActiveRecord'

  { model_name: model_name, method_name: method_name,
    query_key: "#{model_name}.#{method_name}".freeze }
end

.parse_sql_context(sql) ⇒ Object

Parses raw SQL (payload == “SQL”) to extract model context. Used for counter cache updates, touch_later, and connection.execute calls that fire sql.active_record with name=“SQL” rather than “Model Method”.

Returns nil when the table cannot be mapped to a known AR model, so callers fall through to the existing skip path.



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/rails_otel_context/activerecord_context.rb', line 348

def parse_sql_context(sql)
  return nil unless sql

  verb = sql[SQL_VERB_RE, 1]&.capitalize
  return nil unless verb

  keyword = case verb
            when 'Update'          then KW_UPDATE
            when 'Insert'          then KW_INTO
            when 'Delete', 'Select' then KW_FROM
            end
  return nil unless keyword

  table      = extract_table_after(sql, keyword)
  model_name = table ? ar_table_model_map[table] : nil

  # Fall back to the virtual "SQL" model when the table cannot be resolved
  # (e.g. SELECT SLEEP(0.2), SELECT 1, raw DDL). This lets the span-name
  # formatter produce "SQL.Select" / "SQL.Update" for tab-group purposes
  # instead of leaving the span unnamed.
  model_name ||= 'SQL'

  { model_name: model_name, method_name: verb,
    query_key: "#{model_name}.#{verb}".freeze }
end

.reset_ar_table_model_map!Object



428
429
430
# File 'lib/rails_otel_context/activerecord_context.rb', line 428

def reset_ar_table_model_map!
  @ar_table_model_map = nil
end

.retroactively_apply_to_span(span, ctx) ⇒ Object

Retroactively applies AR context to a finished span (e.g. PREPARE spans that finished before sql.active_record fired). Uses direct @attributes mutation because span.recording? is false — set_attribute would be a no-op.



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/rails_otel_context/activerecord_context.rb', line 263

def retroactively_apply_to_span(span, ctx)
  attrs = span.instance_variable_get(:@attributes)
  return unless attrs.respond_to?(:store)

  attrs.store('code.activerecord.model',  ctx[:model_name])  if ctx[:model_name]
  attrs.store('code.activerecord.method', ctx[:method_name]) if ctx[:method_name]
  attrs.store('code.activerecord.scope',  ctx[:scope_name])  if ctx[:scope_name]

  formatter = RailsOtelContext.configuration.span_name_formatter
  return unless formatter && span.respond_to?(:name) && attrs.key?('db.system')

  ar_ctx = ctx.dup
  ar_ctx[:code_namespace] = attrs['code.namespace']
  ar_ctx[:code_function]  = attrs['code.function']

  original_name = span.name
  new_name = formatter.call(original_name, ar_ctx)
  return unless new_name && new_name != original_name

  attrs.store('l9.orig.name', original_name)
  span.instance_variable_set(:@name, new_name)
rescue StandardError
  nil
end

.stash_prepare_span(span) ⇒ Object

Called from CallContextProcessor#on_finish when a PREPARE span finishes before its sql.active_record notification. Stashed spans are flushed by Subscriber#start when the notification fires.



247
248
249
# File 'lib/rails_otel_context/activerecord_context.rb', line 247

def stash_prepare_span(span)
  (Thread.current[PENDING_PREPARE_KEY] ||= []) << span
end

.stub_context(context) ⇒ Object

Test helpers: set AR context directly for unit tests.



252
253
254
# File 'lib/rails_otel_context/activerecord_context.rb', line 252

def stub_context(context)
  Thread.current[THREAD_KEY] = context
end

.stub_scope(scope_name) ⇒ Object



256
257
258
# File 'lib/rails_otel_context/activerecord_context.rb', line 256

def stub_scope(scope_name)
  Thread.current[SCOPE_THREAD_KEY] = scope_name
end