From fdec25a8364da00314ec32772289c26e4734e3b2 Mon Sep 17 00:00:00 2001 From: Dmitry Rybakov <160598371+comandeo-mongo@users.noreply.github.com> Date: Thu, 17 Sep 2026 09:43:27 +0200 Subject: [PATCH 01/11] RUBY-3952 Split command span attributes by cost, freeze per-connection invariants --- .../tracing/open_telemetry/command_tracer.rb | 84 ++++++++++------- .../open_telemetry/command_tracer_spec.rb | 93 +++++++++++++++---- spec/support/tracing.rb | 7 ++ 3 files changed, 133 insertions(+), 51 deletions(-) diff --git a/lib/mongo/tracing/open_telemetry/command_tracer.rb b/lib/mongo/tracing/open_telemetry/command_tracer.rb index 27585839de..04579e8df8 100644 --- a/lib/mongo/tracing/open_telemetry/command_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/command_tracer.rb @@ -72,6 +72,7 @@ def trace_command(message, _operation_context, connection) # the transaction span. Don't pass with_parent to use automatic parent resolution # from the currently active span (the operation span). span = create_command_span(message, connection) + apply_deferred_attributes(span, message) if span.recording? ::OpenTelemetry::Trace.with_span(span) do |s, c| yield.tap do |result| process_command_result(result, cursor_id(message), c, s) @@ -142,61 +143,74 @@ def handle_command_exception(span, exception) span.status = ::OpenTelemetry::Trace::Status.error("Unhandled exception of type: #{exception.class}") end - # Builds span attributes for the command. + # Builds the attributes passed at span creation: the cheap, + # sampler-plausible set. Expensive attributes are deferred to + # apply_deferred_attributes — building them here would defeat the + # sampler's purpose, and on a non-recording span they would be + # discarded anyway. Keys whose value is nil are omitted rather than + # compacted afterwards, so the common case allocates nothing extra. # # @param message [ Mongo::Protocol::Message ] the command message. # @param connection [ Mongo::Server::Connection ] the connection. # # @return [ Hash ] OpenTelemetry span attributes following MongoDB semantic conventions. def span_attributes(message, connection) - base_attributes(message) - .merge(connection_attributes(connection)) - .merge(session_attributes(message)) - .compact - end - - # Returns base database and command attributes. - # - # @param message [ Mongo::Protocol::Message ] the command message. - # - # @return [ Hash ] base span attributes. - def base_attributes(message) - { + attrs = { 'db.system.name' => 'mongodb', 'db.namespace' => database(message), - 'db.collection.name' => collection_name(message), - 'db.command.name' => command_name(message), - 'db.query.summary' => query_summary(message), - 'db.query.text' => query_text(message) + 'db.command.name' => command_name(message) } + if (coll_name = collection_name(message)) + attrs['db.collection.name'] = coll_name + end + attrs.merge(connection_attributes(connection)) end - # Returns connection-related attributes. + # Returns connection-related attributes, computed once per connection + # and frozen. Setting the ivar from here is a benign race: competing + # threads build identical frozen hashes. The value dies with the + # connection, so no cleanup is needed. # # @param connection [ Mongo::Server::Connection ] the connection. # # @return [ Hash ] connection span attributes. def connection_attributes(connection) - { - 'server.port' => connection.address.port, - 'server.address' => connection.address.host, - 'network.transport' => connection.transport.to_s, - 'db.mongodb.server_connection_id' => connection.server.description.server_connection_id, - 'db.mongodb.driver_connection_id' => connection.id - } + attrs = connection.instance_variable_get(:@otel_connection_attributes) + unless attrs + attrs = { + 'server.port' => connection.address.port, + 'server.address' => connection.address.host, + 'network.transport' => connection.transport.to_s, + 'db.mongodb.server_connection_id' => connection.server.description.server_connection_id, + 'db.mongodb.driver_connection_id' => connection.id + }.freeze + connection.instance_variable_set(:@otel_connection_attributes, attrs) + end + attrs end - # Returns session and transaction attributes. + # Sets the expensive attributes after span creation. Only called for + # recording spans: on non-recording spans set_attribute discards. + # Note for reviewers: these attributes are invisible to the sampler, + # which only sees what is passed to start_span. The built-in samplers + # do not read attributes, and db.query.text is off by default. # + # @param span [ OpenTelemetry::Trace::Span ] the current span. # @param message [ Mongo::Protocol::Message ] the command message. - # - # @return [ Hash ] session span attributes. - def session_attributes(message) - { - 'db.mongodb.cursor_id' => cursor_id(message), - 'db.mongodb.lsid' => lsid(message), - 'db.mongodb.txn_number' => txn_number(message) - } + def apply_deferred_attributes(span, message) + span.set_attribute('db.query.summary', query_summary(message)) + if (text = query_text(message)) + span.set_attribute('db.query.text', text) + end + if (lsid_value = lsid(message)) + span.set_attribute('db.mongodb.lsid', lsid_value) + end + if (cursor = cursor_id(message)) + span.set_attribute('db.mongodb.cursor_id', cursor) + end + if (txn = txn_number(message)) + span.set_attribute('db.mongodb.txn_number', txn) + end end # Processes cursor context from the command result. diff --git a/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb b/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb index 28ac8b36fb..2543f4c2bd 100644 --- a/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb +++ b/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb @@ -65,7 +65,9 @@ end describe '#trace_command' do - let(:span) { instance_double(OpenTelemetry::Trace::Span, finish: nil, set_attribute: nil) } + let(:span) do + instance_double(OpenTelemetry::Trace::Span, finish: nil, set_attribute: nil, recording?: true) + end let(:context) { instance_double(Mongo::Operation::Context) } let(:result) { instance_double(Mongo::Operation::Result, cursor_id: 0, successful?: true) } @@ -101,6 +103,41 @@ command_tracer.trace_command(message, operation_context, connection) { result } end + it 'passes only cheap attributes to start_span' do + expect(otel_tracer).to receive(:start_span).with( + 'find', + attributes: hash_excluding('db.query.summary', 'db.query.text', 'db.mongodb.lsid', + 'db.mongodb.cursor_id', 'db.mongodb.txn_number'), + kind: :client + ) + command_tracer.trace_command(message, operation_context, connection) { result } + end + + it 'sets deferred attributes when the span is recording' do + expect(span).to receive(:set_attribute).with('db.query.summary', 'find test_db.users') + expect(span).to receive(:set_attribute).with('db.mongodb.lsid', lsid_value) + command_tracer.trace_command(message, operation_context, connection) { result } + end + + context 'with a non-recording span' do + let(:span) do + instance_double(OpenTelemetry::Trace::Span, finish: nil, set_attribute: nil, recording?: false) + end + + it 'does not build deferred attributes' do + expect(span).not_to receive(:set_attribute) + command_tracer.trace_command(message, operation_context, connection) { result } + end + end + + it 'memoizes connection attributes per connection' do + command_tracer.trace_command(message, operation_context, connection) { result } + command_tracer.trace_command(message, operation_context, connection) { result } + + attrs = connection.instance_variable_get(:@otel_connection_attributes) + expect(attrs).to be_frozen + end + context 'when result has cursor_id' do let(:result) do instance_double(Mongo::Operation::Result, cursor_id: 789, successful?: true) @@ -306,8 +343,11 @@ expect(subject['db.command.name']).to eq('find') end - it 'includes db.query.summary' do - expect(subject['db.query.summary']).to eq('find test_db.users') + it 'excludes deferred attributes' do + %w[db.query.summary db.query.text db.mongodb.lsid db.mongodb.cursor_id + db.mongodb.txn_number].each do |key| + expect(subject).not_to have_key(key) + end end it 'includes server.port' do @@ -330,14 +370,33 @@ expect(subject['db.mongodb.driver_connection_id']).to eq(123) end - it 'includes db.mongodb.lsid' do - expect(subject['db.mongodb.lsid']).to eq(lsid_value) + context 'with an admin command without a collection' do + let(:document) { { 'serverStatus' => 1, '$db' => 'admin' } } + + it 'omits db.collection.name instead of setting nil' do + expect(subject).not_to have_key('db.collection.name') + end + end + end + + describe '#apply_deferred_attributes' do + let(:deferred_span) { instance_double(OpenTelemetry::Trace::Span, set_attribute: nil) } + + it 'sets the query summary' do + expect(deferred_span).to receive(:set_attribute).with('db.query.summary', 'find test_db.users') + command_tracer.send(:apply_deferred_attributes, deferred_span, message) + end + + it 'sets the lsid' do + expect(deferred_span).to receive(:set_attribute).with('db.mongodb.lsid', lsid_value) + command_tracer.send(:apply_deferred_attributes, deferred_span, message) end - it 'does not include nil values' do - expect(subject).not_to have_key('db.mongodb.cursor_id') - expect(subject).not_to have_key('db.mongodb.txn_number') - expect(subject).not_to have_key('db.query.text') + it 'skips attributes that are absent from the command' do + expect(deferred_span).not_to receive(:set_attribute).with('db.mongodb.cursor_id', anything) + expect(deferred_span).not_to receive(:set_attribute).with('db.mongodb.txn_number', anything) + expect(deferred_span).not_to receive(:set_attribute).with('db.query.text', anything) + command_tracer.send(:apply_deferred_attributes, deferred_span, message) end context 'with getMore command' do @@ -349,8 +408,9 @@ } end - it 'includes db.mongodb.cursor_id' do - expect(subject['db.mongodb.cursor_id']).to eq(999) + it 'sets the cursor id' do + expect(deferred_span).to receive(:set_attribute).with('db.mongodb.cursor_id', 999) + command_tracer.send(:apply_deferred_attributes, deferred_span, message) end end @@ -363,17 +423,18 @@ } end - it 'includes db.mongodb.txn_number' do - expect(subject['db.mongodb.txn_number']).to eq(42) + it 'sets the transaction number' do + expect(deferred_span).to receive(:set_attribute).with('db.mongodb.txn_number', 42) + command_tracer.send(:apply_deferred_attributes, deferred_span, message) end end context 'with query text enabled' do let(:query_text_max_length) { 1000 } - it 'includes db.query.text' do - expect(subject['db.query.text']).to be_a(String) - expect(subject['db.query.text']).to include('find') + it 'sets the query text' do + expect(deferred_span).to receive(:set_attribute).with('db.query.text', a_string_including('find')) + command_tracer.send(:apply_deferred_attributes, deferred_span, message) end end end diff --git a/spec/support/tracing.rb b/spec/support/tracing.rb index 6eb96801da..6360f36336 100644 --- a/spec/support/tracing.rb +++ b/spec/support/tracing.rb @@ -22,6 +22,13 @@ def set_attribute(key, value) @attributes[key] = value end + # Mirrors the OpenTelemetry Span API: these spans always record, so the + # driver's deferred-attribute path runs and the assertions see the + # attributes. + def recording? + true + end + # rubocop:disable Lint/UnusedMethodArgument def record_exception(exception, attributes: nil) set_attribute('exception.type', exception.class.to_s) From f434ca0983aeec8fb3728f0ae182d8764c23c67b Mon Sep 17 00:00:00 2001 From: Dmitry Rybakov <160598371+comandeo-mongo@users.noreply.github.com> Date: Thu, 17 Sep 2026 10:44:01 +0200 Subject: [PATCH 02/11] RUBY-3952 Skip span work for spans with invalid contexts --- .../tracing/open_telemetry/command_tracer.rb | 9 +++++ .../open_telemetry/command_tracer_spec.rb | 37 ++++++++++++++++++- spec/support/tracing.rb | 8 ++++ 3 files changed, 52 insertions(+), 2 deletions(-) diff --git a/lib/mongo/tracing/open_telemetry/command_tracer.rb b/lib/mongo/tracing/open_telemetry/command_tracer.rb index 04579e8df8..614b60d4f6 100644 --- a/lib/mongo/tracing/open_telemetry/command_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/command_tracer.rb @@ -72,6 +72,15 @@ def trace_command(message, _operation_context, connection) # the transaction span. Don't pass with_parent to use automatic parent resolution # from the currently active span (the operation span). span = create_command_span(message, connection) + # An invalid context has no trace identity: it cannot be propagated, + # continued, or correlated with anything downstream, so every + # operation on it is waste. This is a state check on the span we + # were handed, not detection of whether the SDK is available — a + # custom API-only provider returning real spans sees the full path. + # Must not key on recording?: an unsampled-but-valid context still + # has to be made current for propagation. + return yield unless span.context.valid? + apply_deferred_attributes(span, message) if span.recording? ::OpenTelemetry::Trace.with_span(span) do |s, c| yield.tap do |result| diff --git a/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb b/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb index 2543f4c2bd..677e9d5d1c 100644 --- a/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb +++ b/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb @@ -65,8 +65,10 @@ end describe '#trace_command' do + let(:span_context) { instance_double(OpenTelemetry::Trace::SpanContext, valid?: true) } let(:span) do - instance_double(OpenTelemetry::Trace::Span, finish: nil, set_attribute: nil, recording?: true) + instance_double(OpenTelemetry::Trace::Span, finish: nil, set_attribute: nil, recording?: true, + context: span_context) end let(:context) { instance_double(Mongo::Operation::Context) } let(:result) { instance_double(Mongo::Operation::Result, cursor_id: 0, successful?: true) } @@ -121,7 +123,8 @@ context 'with a non-recording span' do let(:span) do - instance_double(OpenTelemetry::Trace::Span, finish: nil, set_attribute: nil, recording?: false) + instance_double(OpenTelemetry::Trace::Span, finish: nil, set_attribute: nil, recording?: false, + context: span_context) end it 'does not build deferred attributes' do @@ -138,6 +141,36 @@ expect(attrs).to be_frozen end + context 'with an invalid span (no SDK installed)' do + let(:invalid_span) { OpenTelemetry::Trace::Span::INVALID } + + before do + allow(otel_tracer).to receive(:start_span).and_return(invalid_span) + end + + it 'does not attach the span to the context' do + expect(OpenTelemetry::Trace).not_to receive(:with_span) + command_tracer.trace_command(message, operation_context, connection) { result } + end + + it 'returns the block result unchanged' do + return_value = command_tracer.trace_command(message, operation_context, connection) { :done } + expect(return_value).to eq(:done) + end + + it 'finishes the span' do + expect(invalid_span).to receive(:finish) + command_tracer.trace_command(message, operation_context, connection) { result } + end + + # Guards against an opentelemetry-api upgrade changing no-SDK semantics. + # If this fails, re-evaluate the short-circuit: it degrades to a no-op, + # correctness is unaffected. + it 'pins the API behavior: no-SDK spans have invalid contexts' do + expect(invalid_span.context.valid?).to be false + end + end + context 'when result has cursor_id' do let(:result) do instance_double(Mongo::Operation::Result, cursor_id: 789, successful?: true) diff --git a/spec/support/tracing.rb b/spec/support/tracing.rb index 6360f36336..36befc8df9 100644 --- a/spec/support/tracing.rb +++ b/spec/support/tracing.rb @@ -29,6 +29,10 @@ def recording? true end + def context + @context ||= Context.new(self) + end + # rubocop:disable Lint/UnusedMethodArgument def record_exception(exception, attributes: nil) set_attribute('exception.type', exception.class.to_s) @@ -60,6 +64,10 @@ class Context def initialize(span) @span = span end + + def valid? + true + end end class Tracer From cbb0a6d842369a7045a94cdbbb4f3e8d7d4e5b5a Mon Sep 17 00:00:00 2001 From: Dmitry Rybakov <160598371+comandeo-mongo@users.noreply.github.com> Date: Thu, 17 Sep 2026 10:52:42 +0200 Subject: [PATCH 03/11] RUBY-3952 Hoist message extraction, cache lsid UUID formatting --- .../tracing/open_telemetry/command_tracer.rb | 139 +++++++++++------- .../open_telemetry/command_tracer_spec.rb | 65 ++++++-- 2 files changed, 134 insertions(+), 70 deletions(-) diff --git a/lib/mongo/tracing/open_telemetry/command_tracer.rb b/lib/mongo/tracing/open_telemetry/command_tracer.rb index 614b60d4f6..edb906dbbc 100644 --- a/lib/mongo/tracing/open_telemetry/command_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/command_tracer.rb @@ -30,6 +30,9 @@ class CommandTracer # would only add noise to traces. HELLO_COMMANDS = %w[hello ismaster isMaster].freeze + # Upper bound of the lsid UUID memo cache (see #lsid). + LSID_CACHE_MAX = 128 + # Initializes a new CommandTracer. # # @param otel_tracer [ OpenTelemetry::Trace::Tracer ] the OpenTelemetry tracer. @@ -41,6 +44,8 @@ def initialize(otel_tracer, parent_tracer, query_text_max_length: 0) @otel_tracer = otel_tracer @parent_tracer = parent_tracer @query_text_max_length = query_text_max_length + @lsid_cache = {} + @lsid_cache_mutex = Mutex.new end # Starts a span for a MongoDB command. @@ -66,12 +71,16 @@ def start_span(message, operation_context, connection); end # @return [ Object ] the result of the command. # rubocop:disable Lint/RescueException def trace_command(message, _operation_context, connection) - return yield if skip_tracing?(message) + # The command document and name are extracted once and threaded + # through: the extraction helpers below allocate on every call. + doc = message.documents.first + name = command_name(doc) + return yield if skip_tracing?(doc, name) # Commands should always be nested under their operation span, not directly under # the transaction span. Don't pass with_parent to use automatic parent resolution # from the currently active span (the operation span). - span = create_command_span(message, connection) + span = create_command_span(name, doc, connection) # An invalid context has no trace identity: it cannot be propagated, # continued, or correlated with anything downstream, so every # operation on it is waste. This is a state check on the span we @@ -81,10 +90,11 @@ def trace_command(message, _operation_context, connection) # has to be made current for propagation. return yield unless span.context.valid? - apply_deferred_attributes(span, message) if span.recording? + cursor = cursor_id(name, doc) + apply_deferred_attributes(span, message, name, doc, cursor) if span.recording? ::OpenTelemetry::Trace.with_span(span) do |s, c| yield.tap do |result| - process_command_result(result, cursor_id(message), c, s) + process_command_result(result, cursor, c, s) end end rescue Exception => e @@ -103,26 +113,27 @@ def trace_command(message, _operation_context, connection) # command spans for them. Hello / legacy hello are also skipped to keep # handshake traffic out of traces. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param doc [ Hash ] the command document. + # @param name [ String ] the command name. # # @return [ Boolean ] true when no command span should be created. - def skip_tracing?(message) - name = command_name(message) + def skip_tracing?(doc, name) return true if HELLO_COMMANDS.include?(name) - sensitive?(command_name: name, document: message.documents.first) + sensitive?(command_name: name, document: doc) end # Creates a span for a command. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param name [ String ] the command name. + # @param doc [ Hash ] the command document. # @param connection [ Mongo::Server::Connection ] the connection. # # @return [ OpenTelemetry::Trace::Span ] the created span. - def create_command_span(message, connection) + def create_command_span(name, doc, connection) @otel_tracer.start_span( - command_name(message), - attributes: span_attributes(message, connection), + name, + attributes: span_attributes(doc, name, connection), kind: :client ) end @@ -159,17 +170,18 @@ def handle_command_exception(span, exception) # discarded anyway. Keys whose value is nil are omitted rather than # compacted afterwards, so the common case allocates nothing extra. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param doc [ Hash ] the command document. + # @param name [ String ] the command name. # @param connection [ Mongo::Server::Connection ] the connection. # # @return [ Hash ] OpenTelemetry span attributes following MongoDB semantic conventions. - def span_attributes(message, connection) + def span_attributes(doc, name, connection) attrs = { 'db.system.name' => 'mongodb', - 'db.namespace' => database(message), - 'db.command.name' => command_name(message) + 'db.namespace' => database(doc), + 'db.command.name' => name } - if (coll_name = collection_name(message)) + if (coll_name = collection_name(name, doc)) attrs['db.collection.name'] = coll_name end attrs.merge(connection_attributes(connection)) @@ -206,18 +218,21 @@ def connection_attributes(connection) # # @param span [ OpenTelemetry::Trace::Span ] the current span. # @param message [ Mongo::Protocol::Message ] the command message. - def apply_deferred_attributes(span, message) - span.set_attribute('db.query.summary', query_summary(message)) + # @param name [ String ] the command name. + # @param doc [ Hash ] the command document. + # @param cursor [ Integer | nil ] the cursor id, extracted once per command. + def apply_deferred_attributes(span, message, name, doc, cursor) + span.set_attribute('db.query.summary', query_summary(name, doc)) if (text = query_text(message)) span.set_attribute('db.query.text', text) end - if (lsid_value = lsid(message)) + if (lsid_value = lsid(doc)) span.set_attribute('db.mongodb.lsid', lsid_value) end - if (cursor = cursor_id(message)) + unless cursor.nil? span.set_attribute('db.mongodb.cursor_id', cursor) end - if (txn = txn_number(message)) + if (txn = txn_number(doc)) span.set_attribute('db.mongodb.txn_number', txn) end end @@ -265,51 +280,53 @@ def maybe_trace_error(result, span) # Generates a summary string for the query. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param name [ String ] the command name. + # @param doc [ Hash ] the command document. # # @return [ String ] summary in format "command_name db.collection" or "command_name db". - def query_summary(message) - if (coll_name = collection_name(message)) - "#{command_name(message)} #{database(message)}.#{coll_name}" + def query_summary(name, doc) + if (coll_name = collection_name(name, doc)) + "#{name} #{database(doc)}.#{coll_name}" else - "#{command_name(message)} #{database(message)}" + "#{name} #{database(doc)}" end end - # Extracts the collection name from the command message. + # Extracts the collection name from the command document. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param name [ String ] the command name. + # @param doc [ Hash ] the command document. # # @return [ String | nil ] the collection name, or nil if not applicable. - def collection_name(message) - case command_name(message) + def collection_name(name, doc) + case name when 'getMore' - message.documents.first['collection'].to_s + doc['collection'].to_s when 'listCollections', 'listDatabases', 'commitTransaction', 'abortTransaction' nil else - value = message.documents.first.values.first + value = doc.values.first # Return nil if the value is not a string (e.g., for admin commands that have numeric values) value.is_a?(String) ? value : nil end end - # Extracts the command name from the message. + # Extracts the command name from the command document. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param doc [ Hash ] the command document. # # @return [ String ] the command name. - def command_name(message) - message.documents.first.keys.first.to_s + def command_name(doc) + doc.keys.first.to_s end - # Extracts the database name from the message. + # Extracts the database name from the command document. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param doc [ Hash ] the command document. # # @return [ String ] the database name. - def database(message) - message.documents.first['$db'].to_s + def database(doc) + doc['$db'].to_s end # Checks if query text capture is enabled. @@ -321,34 +338,48 @@ def query_text? # Extracts the cursor ID from getMore commands. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param name [ String ] the command name. + # @param doc [ Hash ] the command document. # # @return [ Integer | nil ] the cursor ID, or nil if not a getMore command. - def cursor_id(message) - return unless command_name(message) == 'getMore' + def cursor_id(name, doc) + return unless name == 'getMore' - message.documents.first['getMore'].value + doc['getMore'].value end - # Extracts the logical session ID from the command. + # Extracts the logical session ID from the command. The UUID string + # is formatted once per session id and memoized in a bounded cache: + # the value is invariant for the life of a session, and formatting it + # per command showed up in the DRIVERS-3620 profile. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param doc [ Hash ] the command document. # - # @return [ BSON::Binary | nil ] the session ID, or nil if not present. - def lsid(message) - lsid_doc = message.documents.first['lsid'] + # @return [ String | nil ] the session ID as a UUID string, or nil if not present. + def lsid(doc) + lsid_doc = doc['lsid'] return unless lsid_doc - lsid_doc['id'].to_uuid + binary = lsid_doc['id'] + key = binary.data + cached = @lsid_cache_mutex.synchronize { @lsid_cache[key] } + return cached if cached + + uuid = binary.to_uuid + @lsid_cache_mutex.synchronize do + @lsid_cache.clear if @lsid_cache.size >= LSID_CACHE_MAX + @lsid_cache[key] = uuid + end + uuid end # Extracts the transaction number from the command. # - # @param message [ Mongo::Protocol::Message ] the command message. + # @param doc [ Hash ] the command document. # # @return [ Integer | nil ] the transaction number, or nil if not present. - def txn_number(message) - txn_num = message.documents.first['txnNumber'] + def txn_number(doc) + txn_num = doc['txnNumber'] return unless txn_num txn_num.value diff --git a/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb b/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb index 677e9d5d1c..e324202b6e 100644 --- a/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb +++ b/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb @@ -141,6 +141,28 @@ expect(attrs).to be_frozen end + it 'extracts the command document once per command' do + count = 0 + allow(message).to receive(:documents) do + count += 1 + [ document ] + end + command_tracer.trace_command(message, operation_context, connection) { result } + expect(count).to eq(1) + end + + it 'formats the lsid UUID once across repeated commands' do + count = 0 + allow(document['lsid']['id']).to receive(:to_uuid) do + count += 1 + lsid_value + end + 3.times do + command_tracer.trace_command(message, operation_context, connection) { result } + end + expect(count).to eq(1) + end + context 'with an invalid span (no SDK installed)' do let(:invalid_span) { OpenTelemetry::Trace::Span::INVALID } @@ -358,7 +380,7 @@ end describe '#span_attributes' do - subject { command_tracer.send(:span_attributes, message, connection) } + subject { command_tracer.send(:span_attributes, document, 'find', connection) } it 'includes db.system.name' do expect(subject['db.system.name']).to eq('mongodb') @@ -417,19 +439,19 @@ it 'sets the query summary' do expect(deferred_span).to receive(:set_attribute).with('db.query.summary', 'find test_db.users') - command_tracer.send(:apply_deferred_attributes, deferred_span, message) + command_tracer.send(:apply_deferred_attributes, deferred_span, message, 'find', document, nil) end it 'sets the lsid' do expect(deferred_span).to receive(:set_attribute).with('db.mongodb.lsid', lsid_value) - command_tracer.send(:apply_deferred_attributes, deferred_span, message) + command_tracer.send(:apply_deferred_attributes, deferred_span, message, 'find', document, nil) end it 'skips attributes that are absent from the command' do expect(deferred_span).not_to receive(:set_attribute).with('db.mongodb.cursor_id', anything) expect(deferred_span).not_to receive(:set_attribute).with('db.mongodb.txn_number', anything) expect(deferred_span).not_to receive(:set_attribute).with('db.query.text', anything) - command_tracer.send(:apply_deferred_attributes, deferred_span, message) + command_tracer.send(:apply_deferred_attributes, deferred_span, message, 'find', document, nil) end context 'with getMore command' do @@ -443,7 +465,7 @@ it 'sets the cursor id' do expect(deferred_span).to receive(:set_attribute).with('db.mongodb.cursor_id', 999) - command_tracer.send(:apply_deferred_attributes, deferred_span, message) + command_tracer.send(:apply_deferred_attributes, deferred_span, message, 'getMore', document, 999) end end @@ -458,7 +480,7 @@ it 'sets the transaction number' do expect(deferred_span).to receive(:set_attribute).with('db.mongodb.txn_number', 42) - command_tracer.send(:apply_deferred_attributes, deferred_span, message) + command_tracer.send(:apply_deferred_attributes, deferred_span, message, 'find', document, nil) end end @@ -467,15 +489,16 @@ it 'sets the query text' do expect(deferred_span).to receive(:set_attribute).with('db.query.text', a_string_including('find')) - command_tracer.send(:apply_deferred_attributes, deferred_span, message) + command_tracer.send(:apply_deferred_attributes, deferred_span, message, 'find', document, nil) end end end describe '#collection_name' do - subject { command_tracer.send(:collection_name, message) } + subject { command_tracer.send(:collection_name, name, document) } context 'with find command' do + let(:name) { 'find' } let(:document) { { 'find' => 'users' } } it 'returns the collection name' do @@ -484,6 +507,7 @@ end context 'with getMore command' do + let(:name) { 'getMore' } let(:document) { { 'getMore' => 123, 'collection' => 'users' } } it 'returns the collection name' do @@ -492,6 +516,7 @@ end context 'with listCollections command' do + let(:name) { 'listCollections' } let(:document) { { 'listCollections' => 1 } } it 'returns nil' do @@ -500,6 +525,7 @@ end context 'with listDatabases command' do + let(:name) { 'listDatabases' } let(:document) { { 'listDatabases' => 1 } } it 'returns nil' do @@ -508,6 +534,7 @@ end context 'with commitTransaction command' do + let(:name) { 'commitTransaction' } let(:document) { { 'commitTransaction' => 1 } } it 'returns nil' do @@ -516,6 +543,7 @@ end context 'with abortTransaction command' do + let(:name) { 'abortTransaction' } let(:document) { { 'abortTransaction' => 1 } } it 'returns nil' do @@ -524,6 +552,7 @@ end context 'with admin command with numeric value' do + let(:name) { 'serverStatus' } let(:document) { { 'serverStatus' => 1 } } it 'returns nil' do @@ -533,7 +562,7 @@ end describe '#command_name' do - subject { command_tracer.send(:command_name, message) } + subject { command_tracer.send(:command_name, document) } let(:document) { { 'find' => 'users' } } @@ -543,7 +572,7 @@ end describe '#database' do - subject { command_tracer.send(:database, message) } + subject { command_tracer.send(:database, document) } let(:document) { { 'find' => 'users', '$db' => 'test_db' } } @@ -553,9 +582,9 @@ end describe '#query_summary' do - subject { command_tracer.send(:query_summary, message) } - context 'with collection name' do + subject { command_tracer.send(:query_summary, 'find', document) } + let(:document) { { 'find' => 'users', '$db' => 'test_db' } } it 'includes collection name' do @@ -564,6 +593,8 @@ end context 'without collection name' do + subject { command_tracer.send(:query_summary, 'listCollections', document) } + let(:document) { { 'listCollections' => 1, '$db' => 'test_db' } } it 'does not include collection name' do @@ -573,9 +604,9 @@ end describe '#cursor_id' do - subject { command_tracer.send(:cursor_id, message) } - context 'with getMore command' do + subject { command_tracer.send(:cursor_id, 'getMore', document) } + let(:document) { { 'getMore' => BSON::Int64.new(999) } } it 'returns the cursor ID' do @@ -584,6 +615,8 @@ end context 'with find command' do + subject { command_tracer.send(:cursor_id, 'find', document) } + let(:document) { { 'find' => 'users' } } it 'returns nil' do @@ -593,7 +626,7 @@ end describe '#lsid' do - subject { command_tracer.send(:lsid, message) } + subject { command_tracer.send(:lsid, document) } context 'with lsid present' do let(:document) { { 'find' => 'users', 'lsid' => { 'id' => BSON::Binary.from_uuid(lsid_value) } } } @@ -613,7 +646,7 @@ end describe '#txn_number' do - subject { command_tracer.send(:txn_number, message) } + subject { command_tracer.send(:txn_number, document) } context 'with txnNumber present' do let(:document) { { 'find' => 'users', 'txnNumber' => BSON::Int64.new(42) } } From abc7f48e5bb6f66a2cf4be2726fe5a7aec2704ac Mon Sep 17 00:00:00 2001 From: Dmitry Rybakov <160598371+comandeo-mongo@users.noreply.github.com> Date: Thu, 17 Sep 2026 11:17:31 +0200 Subject: [PATCH 04/11] RUBY-3952 Apply attribute split and invalid-context short-circuit to OperationTracer --- .../open_telemetry/operation_tracer.rb | 60 ++++--- .../open_telemetry/operation_tracer_spec.rb | 153 ++++++++++-------- 2 files changed, 129 insertions(+), 84 deletions(-) diff --git a/lib/mongo/tracing/open_telemetry/operation_tracer.rb b/lib/mongo/tracing/open_telemetry/operation_tracer.rb index 2800fcd1e6..dcde83ec0f 100644 --- a/lib/mongo/tracing/open_telemetry/operation_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/operation_tracer.rb @@ -57,6 +57,20 @@ def initialize(otel_tracer, parent_tracer) # rubocop:disable Lint/RescueException def trace_operation(operation, operation_context, op_name: nil, &block) span = create_operation_span(operation, operation_context, op_name) + # An invalid context has no trace identity: it cannot be propagated, + # continued, or correlated with anything downstream, so every + # operation on it is waste. This is a state check on the span we + # were handed, not detection of whether the SDK is available — a + # custom API-only provider returning real spans sees the full path. + # Must not key on recording?: an unsampled-but-valid context still + # has to be made current for propagation. Skipping here also leaves + # the cursor context map untouched, consistent with tracing being + # effectively off. + return yield unless span.context.valid? + + if span.recording? && !operation.cursor_id.nil? + span.set_attribute('db.mongodb.cursor_id', operation.cursor_id) + end execute_with_span(span, operation, &block) rescue Exception => e handle_span_exception(span, e) @@ -68,7 +82,9 @@ def trace_operation(operation, operation_context, op_name: nil, &block) private - # Creates an OpenTelemetry span for the operation. + # Creates an OpenTelemetry span for the operation. The operation name, + # collection name and span name are each computed once and reused + # between the span name and the attributes. # # @param operation [ Mongo::Operation ] the operation. # @param operation_context [ Mongo::Operation::Context ] the operation context. @@ -77,9 +93,12 @@ def trace_operation(operation, operation_context, op_name: nil, &block) # @return [ OpenTelemetry::Trace::Span ] the created span. def create_operation_span(operation, operation_context, op_name) parent_context = parent_context_for(operation_context, operation.cursor_id) + name = operation_name(operation, op_name) + coll_name = collection_name(operation) + span_name = operation_span_name(name, operation.db_name, coll_name) @otel_tracer.start_span( - operation_span_name(operation, op_name), - attributes: span_attributes(operation, op_name), + span_name, + attributes: span_attributes(operation, name, span_name, coll_name), with_parent: parent_context, kind: :client ) @@ -124,21 +143,26 @@ def operation_name(operation, op_name = nil) op_name || operation.class.name.split('::').last.downcase end - # Builds span attributes for the operation. + # Builds the attributes passed at span creation: the cheap set. The + # cursor id is deferred to trace_operation (behind recording?) — on a + # non-recording span set_attribute discards, and the sampler has no + # use for it. # # @param operation [ Mongo::Operation ] the operation. - # @param op_name [ String | nil ] optional operation name. + # @param name [ String ] the operation name. + # @param span_name [ String ] the span name, reused as the summary. + # @param coll_name [ String | nil ] the collection name, computed once. # # @return [ Hash ] OpenTelemetry span attributes following MongoDB semantic conventions. - def span_attributes(operation, op_name) - { + def span_attributes(operation, name, span_name, coll_name) + attrs = { 'db.system.name' => 'mongodb', 'db.namespace' => operation.db_name.to_s, - 'db.collection.name' => collection_name(operation), - 'db.operation.name' => operation_name(operation, op_name), - 'db.operation.summary' => operation_span_name(operation, op_name), - 'db.mongodb.cursor_id' => operation.cursor_id, - }.compact + 'db.operation.name' => name, + 'db.operation.summary' => span_name + } + attrs['db.collection.name'] = coll_name unless coll_name.nil? + attrs end # Processes cursor context after operation execution. @@ -209,16 +233,16 @@ def collection_key_for_operation(operation) # Generates the span name for the operation. # - # @param operation [ Mongo::Operation ] the operation. - # @param op_name [ String | nil ] optional operation name. + # @param name [ String ] the operation name. + # @param db_name [ String ] the database name. + # @param coll_name [ String | nil ] the collection name, if any. # # @return [ String ] span name in format "operation_name db.collection" or "operation_name db". - def operation_span_name(operation, op_name = nil) - coll_name = collection_name(operation) + def operation_span_name(name, db_name, coll_name) if coll_name && !coll_name.empty? - "#{operation_name(operation, op_name)} #{operation.db_name}.#{coll_name}" + "#{name} #{db_name}.#{coll_name}" else - "#{operation_name(operation, op_name)} #{operation.db_name}" + "#{name} #{db_name}" end end end diff --git a/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb b/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb index 0f7f6f2b00..e0f28d640c 100644 --- a/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb +++ b/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb @@ -41,6 +41,8 @@ allow(s).to receive(:set_attribute) allow(s).to receive(:record_exception) allow(s).to receive(:status=) + allow(s).to receive(:context).and_return(double('SpanContext', valid?: true)) + allow(s).to receive(:recording?).and_return(true) end end let(:context) { double('OpenTelemetry::Context') } @@ -91,6 +93,68 @@ operation_tracer.trace_operation(operation, operation_context) { result } end + it 'passes only cheap attributes to start_span' do + expect(otel_tracer).to receive(:start_span).with( + anything, + attributes: hash_excluding('db.mongodb.cursor_id'), + with_parent: nil, + kind: :client + ) + operation_tracer.trace_operation(operation, operation_context) { result } + end + + it 'sets the cursor id after span creation when recording' do + operation = instance_double( + Mongo::Operation::GetMore, + db_name: 'test_db', + coll_name: 'test_collection', + cursor_id: 12_345, + class: class_double(Mongo::Operation::GetMore, name: 'Mongo::Operation::GetMore'), + respond_to?: true + ) + expect(span).to receive(:set_attribute).with('db.mongodb.cursor_id', 12_345) + operation_tracer.trace_operation(operation, operation_context) { result } + end + + context 'with a non-recording span' do + before do + allow(span).to receive(:recording?).and_return(false) + end + + it 'does not set attributes' do + expect(span).not_to receive(:set_attribute) + operation_tracer.trace_operation(operation, operation_context) { result } + end + end + + context 'with an invalid span (no SDK installed)' do + let(:invalid_span) { OpenTelemetry::Trace::Span::INVALID } + + before do + allow(otel_tracer).to receive(:start_span).and_return(invalid_span) + end + + it 'does not attach the span to the context' do + expect(OpenTelemetry::Trace).not_to receive(:with_span) + operation_tracer.trace_operation(operation, operation_context) { result } + end + + it 'returns the block result unchanged' do + return_value = operation_tracer.trace_operation(operation, operation_context) { :done } + expect(return_value).to eq(:done) + end + + it 'leaves the cursor context map untouched' do + operation_tracer.trace_operation(operation, operation_context) { result } + expect(cursor_context_map).to be_empty + end + + it 'finishes the span' do + expect(invalid_span).to receive(:finish) + operation_tracer.trace_operation(operation, operation_context) { result } + end + end + context 'with custom operation name' do it 'uses the provided op_name' do expect(otel_tracer).to receive(:start_span).with( @@ -176,8 +240,11 @@ expect(cursor_context_map).not_to have_key(cursor_id) end - it 'does not set cursor_id attribute' do - expect(span).not_to receive(:set_attribute).with('db.mongodb.cursor_id', anything) + it 'does not set a new cursor_id attribute' do + # The span carries the operation's own cursor id (set after span + # creation, deferred behind recording?); the closed result must not + # add another. + expect(span).to receive(:set_attribute).with('db.mongodb.cursor_id', 999).once operation_tracer.trace_operation(operation, operation_context) { cursor } end end @@ -218,18 +285,19 @@ end describe '#span_attributes' do - subject(:attributes) { operation_tracer.send(:span_attributes, operation, op_name) } + subject(:attributes) do + operation_tracer.send(:span_attributes, operation, name, span_name, coll_name) + end - let(:op_name) { nil } + let(:name) { 'find' } + let(:span_name) { 'find test_db.users' } + let(:coll_name) { 'users' } let(:operation_class) { class_double(Mongo::Operation::Find, name: 'Mongo::Operation::Find') } let(:operation) do instance_double( Mongo::Operation::Find, db_name: 'test_db', - coll_name: 'users', - cursor_id: nil, - class: operation_class, - respond_to?: true + class: operation_class ) end @@ -253,32 +321,22 @@ expect(attributes['db.operation.summary']).to eq('find test_db.users') end - it 'does not include nil values' do + it 'never includes the cursor id' do expect(attributes).not_to have_key('db.mongodb.cursor_id') end - context 'with cursor_id' do - let(:operation_class) { class_double(Mongo::Operation::GetMore, name: 'Mongo::Operation::GetMore') } - let(:operation) do - instance_double( - Mongo::Operation::GetMore, - db_name: 'test_db', - coll_name: 'users', - cursor_id: 12_345, - class: operation_class, - respond_to?: true - ) - end + context 'without a collection name' do + let(:coll_name) { nil } - it 'includes db.mongodb.cursor_id' do - expect(attributes['db.mongodb.cursor_id']).to eq(12_345) + it 'omits db.collection.name instead of setting nil' do + expect(attributes).not_to have_key('db.collection.name') end end - context 'with custom op_name' do - let(:op_name) { 'custom_operation' } + context 'with custom operation name' do + let(:name) { 'custom_operation' } - it 'uses the custom op_name' do + it 'uses the custom operation name' do expect(attributes['db.operation.name']).to eq('custom_operation') end end @@ -496,21 +554,8 @@ end describe '#operation_span_name' do - subject(:span_name) { operation_tracer.send(:operation_span_name, operation, op_name) } - - let(:op_name) { nil } - context 'with collection name' do - let(:operation_class) { class_double(Mongo::Operation::Find, name: 'Mongo::Operation::Find') } - let(:operation) do - instance_double( - Mongo::Operation::Find, - db_name: 'test_db', - coll_name: 'users', - class: operation_class, - respond_to?: true - ) - end + subject(:span_name) { operation_tracer.send(:operation_span_name, 'find', 'test_db', 'users') } it 'includes collection name in format' do expect(span_name).to eq('find test_db.users') @@ -518,22 +563,7 @@ end context 'without collection name' do - let(:operation_class) do - class_double(Mongo::Operation::ListCollections, name: 'Mongo::Operation::ListCollections') - end - let(:operation) do - instance_double( - Mongo::Operation::ListCollections, - db_name: 'test_db', - coll_name: nil, - class: operation_class, - respond_to?: true - ) - end - - before do - allow(operation).to receive(:is_a?).and_return(false) - end + subject(:span_name) { operation_tracer.send(:operation_span_name, 'listcollections', 'test_db', nil) } it 'excludes collection name from format' do expect(span_name).to eq('listcollections test_db') @@ -541,16 +571,7 @@ end context 'with empty collection name' do - let(:operation_class) { class_double(Mongo::Operation::Command, name: 'Mongo::Operation::Command') } - let(:operation) do - instance_double( - Mongo::Operation::Command, - db_name: 'test_db', - coll_name: '', - class: operation_class, - respond_to?: true - ) - end + subject(:span_name) { operation_tracer.send(:operation_span_name, 'command', 'test_db', '') } it 'excludes collection name from format' do expect(span_name).to eq('command test_db') From c59f45c51f1afa8d619ea1a778a968fac98449ae Mon Sep 17 00:00:00 2001 From: Dmitry Rybakov <160598371+comandeo-mongo@users.noreply.github.com> Date: Thu, 17 Sep 2026 13:51:12 +0200 Subject: [PATCH 05/11] RUBY-3952 Memoize operation names, allocation-free command extraction --- lib/mongo/monitoring/event/secure.rb | 7 ++++++- .../tracing/open_telemetry/command_tracer.rb | 20 ++++++++++++++++--- .../open_telemetry/operation_tracer.rb | 11 +++++++++- .../open_telemetry/operation_tracer_spec.rb | 9 +++++++++ 4 files changed, 42 insertions(+), 5 deletions(-) diff --git a/lib/mongo/monitoring/event/secure.rb b/lib/mongo/monitoring/event/secure.rb index 7cc8f38e68..01a92605d6 100644 --- a/lib/mongo/monitoring/event/secure.rb +++ b/lib/mongo/monitoring/event/secure.rb @@ -37,6 +37,11 @@ module Secure copydb ].freeze + # The hello / legacy hello command names, hoisted to a constant: the + # sensitivity check runs on every command event and an array literal + # would allocate on each call. + HELLO_COMMANDS = %w[hello ismaster isMaster].freeze + # Check whether the command is sensitive in terms of command monitoring # spec. A command is detected as sensitive if it is in the # list or if it is a hello/legacy hello command, and @@ -53,7 +58,7 @@ def sensitive?(command_name:, document:) # when speculativeAuthenticate is present, their commands AND replies # MUST be redacted from the events. # See https://github.com/mongodb/specifications/blob/master/source/command-logging-and-monitoring/command-logging-and-monitoring.md#security - %w[hello ismaster isMaster].include?(command_name.to_s) && + HELLO_COMMANDS.include?(command_name.to_s) && !!document['speculativeAuthenticate'] end diff --git a/lib/mongo/tracing/open_telemetry/command_tracer.rb b/lib/mongo/tracing/open_telemetry/command_tracer.rb index edb906dbbc..79bdb737f4 100644 --- a/lib/mongo/tracing/open_telemetry/command_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/command_tracer.rb @@ -305,19 +305,33 @@ def collection_name(name, doc) when 'listCollections', 'listDatabases', 'commitTransaction', 'abortTransaction' nil else - value = doc.values.first + # Iterate instead of using doc.values.first: the block form is + # allocation-free (see #command_name). + value = nil + # rubocop:disable Lint/UnreachableLoop -- intentional: only the first entry is needed + doc.each_value do |v| + value = v + break + end + # rubocop:enable Lint/UnreachableLoop # Return nil if the value is not a string (e.g., for admin commands that have numeric values) value.is_a?(String) ? value : nil end end - # Extracts the command name from the command document. + # Extracts the command name from the command document. Iterates + # instead of using doc.keys.first: the block form is allocation-free, + # while keys builds an array of every top-level key per call — and + # this runs on every traced command. # # @param doc [ Hash ] the command document. # # @return [ String ] the command name. def command_name(doc) - doc.keys.first.to_s + # rubocop:disable Lint/UnreachableLoop -- intentional: only the first entry is needed + doc.each_key { |key| return key.to_s } + # rubocop:enable Lint/UnreachableLoop + '' end # Extracts the database name from the command document. diff --git a/lib/mongo/tracing/open_telemetry/operation_tracer.rb b/lib/mongo/tracing/open_telemetry/operation_tracer.rb index dcde83ec0f..69b58fd64c 100644 --- a/lib/mongo/tracing/open_telemetry/operation_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/operation_tracer.rb @@ -37,6 +37,7 @@ class OperationTracer def initialize(otel_tracer, parent_tracer) @otel_tracer = otel_tracer @parent_tracer = parent_tracer + @operation_names = {} end # Trace a MongoDB operation. @@ -134,13 +135,21 @@ def handle_span_exception(span, exception) end # Returns the operation name from the provided name or operation class. + # The class-derived name is memoized per class: it is invariant and + # deriving it (split + downcase) allocates on every call. The number + # of operation classes is small and fixed, so the cache is unbounded + # by design; a benign race on first computation writes identical + # strings. # # @param operation [ Mongo::Operation ] the operation. # @param op_name [ String | nil ] optional operation name. # # @return [ String ] the operation name in lowercase. def operation_name(operation, op_name = nil) - op_name || operation.class.name.split('::').last.downcase + return op_name if op_name + + klass = operation.class + @operation_names[klass] ||= klass.name.split('::').last.downcase end # Builds the attributes passed at span creation: the cheap set. The diff --git a/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb b/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb index e0f28d640c..d29c584856 100644 --- a/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb +++ b/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb @@ -355,6 +355,15 @@ expect(op_name_result).to eq('find') end + it 'memoizes the operation name per operation class' do + operation_tracer.send(:operation_name, operation, nil) + operation_tracer.send(:operation_name, operation, nil) + + cache = operation_tracer.instance_variable_get(:@operation_names) + expect(cache.size).to eq(1) + expect(cache.values.first).to eq('find') + end + context 'with custom op_name' do let(:op_name) { 'CustomOperation' } From 2f898df11806e014984cb9d30e369ec6d95d24c3 Mon Sep 17 00:00:00 2001 From: Dmitry Rybakov <160598371+comandeo-mongo@users.noreply.github.com> Date: Mon, 21 Sep 2026 11:28:58 +0200 Subject: [PATCH 06/11] RUBY-3952 Cache transaction map keys, drop dead cursor key computation --- .../open_telemetry/operation_tracer.rb | 2 +- lib/mongo/tracing/open_telemetry/tracer.rb | 44 +++++---- .../tracing/open_telemetry/tracer_spec.rb | 92 +++++++++++++++++++ 3 files changed, 114 insertions(+), 24 deletions(-) create mode 100644 spec/mongo/tracing/open_telemetry/tracer_spec.rb diff --git a/lib/mongo/tracing/open_telemetry/operation_tracer.rb b/lib/mongo/tracing/open_telemetry/operation_tracer.rb index 69b58fd64c..f5bc6e2a8d 100644 --- a/lib/mongo/tracing/open_telemetry/operation_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/operation_tracer.rb @@ -93,7 +93,7 @@ def trace_operation(operation, operation_context, op_name: nil, &block) # # @return [ OpenTelemetry::Trace::Span ] the created span. def create_operation_span(operation, operation_context, op_name) - parent_context = parent_context_for(operation_context, operation.cursor_id) + parent_context = parent_context_for(operation_context) name = operation_name(operation, op_name) coll_name = collection_name(operation) span_name = operation_span_name(name, operation.db_name, coll_name) diff --git a/lib/mongo/tracing/open_telemetry/tracer.rb b/lib/mongo/tracing/open_telemetry/tracer.rb index 1def549e52..584df8b2ea 100644 --- a/lib/mongo/tracing/open_telemetry/tracer.rb +++ b/lib/mongo/tracing/open_telemetry/tracer.rb @@ -146,34 +146,20 @@ def cursor_context_map @cursor_context_map ||= {} end - # Generates a unique key for cursor tracking in the context map. - # - # @param session [ Mongo::Session ] the session associated with the cursor. - # @param cursor_id [ Integer ] the cursor ID. - # - # @return [ String | nil ] unique key combining session ID and cursor ID, or nil if either is nil. - def cursor_map_key(session, cursor_id) - return if cursor_id.nil? || session.nil? - - "#{session.session_id['id'].to_uuid}-#{cursor_id}" - end - # Determines the parent OpenTelemetry context for an operation. # - # Returns the transaction context if the operation is part of a transaction, - # otherwise returns nil. Cursor-based context nesting is not currently implemented. + # Returns the transaction context if the operation is part of a + # transaction, otherwise returns nil. Cursor operations deliberately + # have no parent here: a caller-driven getMore must not be nested + # under the span of the operation that created the cursor. # # @param operation_context [ Mongo::Operation::Context ] the operation context. - # @param cursor_id [ Integer ] the cursor ID, if applicable. # # @return [ OpenTelemetry::Context | nil ] parent context or nil. - def parent_context_for(operation_context, cursor_id) - if (key = transaction_map_key(operation_context.session)) - transaction_context_map[key] - elsif (_key = cursor_map_key(operation_context.session, cursor_id)) - # We return nil here unless we decide how to nest cursor operations. - nil - end + def parent_context_for(operation_context) + return unless (key = transaction_map_key(operation_context.session)) + + transaction_context_map[key] end # Returns the transaction context map for tracking active transaction contexts. @@ -200,6 +186,12 @@ def transaction_token_map # Generates a unique key for transaction tracking. # # Returns nil for implicit sessions or sessions not in a transaction. + # The key is invariant for the life of a transaction but is needed on + # every operation span created inside it, and formatting it (a UUID + # plus interpolation) showed the same per-call cost the lsid cache + # removed from the command path. It is memoized on the session, keyed + # by the transaction number, so each transaction formats it once. A + # benign race may format it twice; the results are identical. # # @param session [ Mongo::Session ] the session. # @@ -207,7 +199,13 @@ def transaction_token_map def transaction_map_key(session) return if session.nil? || session.implicit? || !session.in_transaction? - "#{session.session_id['id'].to_uuid}-#{session.txn_num}" + txn_num = session.txn_num + cached = session.instance_variable_get(:@otel_transaction_key) + return cached[1] if cached && cached[0] == txn_num + + key = "#{session.session_id['id'].to_uuid}-#{txn_num}" + session.instance_variable_set(:@otel_transaction_key, [ txn_num, key ].freeze) + key end private diff --git a/spec/mongo/tracing/open_telemetry/tracer_spec.rb b/spec/mongo/tracing/open_telemetry/tracer_spec.rb new file mode 100644 index 0000000000..ddc877ccf6 --- /dev/null +++ b/spec/mongo/tracing/open_telemetry/tracer_spec.rb @@ -0,0 +1,92 @@ +# frozen_string_literal: true + +require 'spec_helper' + +require 'opentelemetry' + +describe Mongo::Tracing::OpenTelemetry::Tracer do + let(:otel_tracer) { double('OpenTelemetry::Trace::Tracer') } + let(:tracer) { described_class.new(enabled: true, otel_tracer: otel_tracer) } + + let(:session_uuid) { 'de124f0e-b9a8-4bfc-8f4e-6d9c8f0a3c1d' } + let(:session_id_binary) { double('BSON::Binary', to_uuid: session_uuid) } + let(:session) do + instance_double( + Mongo::Session, + implicit?: false, + in_transaction?: true, + txn_num: 42, + session_id: { 'id' => session_id_binary } + ) + end + + describe '#transaction_map_key' do + context 'when the session is nil' do + it 'returns nil' do + expect(tracer.transaction_map_key(nil)).to be_nil + end + end + + context 'when the session is implicit' do + let(:session) { instance_double(Mongo::Session, implicit?: true) } + + it 'returns nil' do + expect(tracer.transaction_map_key(session)).to be_nil + end + end + + context 'when the session is not in a transaction' do + let(:session) { instance_double(Mongo::Session, implicit?: false, in_transaction?: false) } + + it 'returns nil' do + expect(tracer.transaction_map_key(session)).to be_nil + end + end + + context 'when the session is in a transaction' do + it 'combines the session UUID and the transaction number' do + expect(tracer.transaction_map_key(session)).to eq("#{session_uuid}-42") + end + + it 'formats the session UUID once across repeated calls' do + expect(session_id_binary).to receive(:to_uuid).once.and_return(session_uuid) + + 3.times { tracer.transaction_map_key(session) } + end + + it 'computes a new key when the transaction number changes' do + expect(tracer.transaction_map_key(session)).to eq("#{session_uuid}-42") + + allow(session).to receive(:txn_num).and_return(43) + expect(tracer.transaction_map_key(session)).to eq("#{session_uuid}-43") + end + end + end + + describe '#parent_context_for' do + let(:operation_context) { instance_double(Mongo::Operation::Context, session: session) } + + context 'when the session is in a transaction' do + it 'returns the transaction context' do + context = double('OpenTelemetry::Context') + tracer.transaction_context_map["#{session_uuid}-42"] = context + + expect(tracer.parent_context_for(operation_context)).to eq(context) + end + + it 'returns nil when the transaction has no stored context' do + expect(tracer.parent_context_for(operation_context)).to be_nil + end + end + + context 'when the session is not in a transaction' do + let(:session) { instance_double(Mongo::Session, implicit?: true) } + + it 'returns nil without formatting a session key' do + expect(session).not_to receive(:session_id) + + expect(tracer.parent_context_for(operation_context)).to be_nil + end + end + end +end From 96c9f0471463e8fe3aedef8b95880e35153b8b5d Mon Sep 17 00:00:00 2001 From: Dmitry Rybakov <160598371+comandeo-mongo@users.noreply.github.com> Date: Mon, 21 Sep 2026 12:05:16 +0200 Subject: [PATCH 07/11] RUBY-3952 Synchronize the operation-name cache --- lib/mongo/tracing/open_telemetry/operation_tracer.rb | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/lib/mongo/tracing/open_telemetry/operation_tracer.rb b/lib/mongo/tracing/open_telemetry/operation_tracer.rb index f5bc6e2a8d..4a9b91db5b 100644 --- a/lib/mongo/tracing/open_telemetry/operation_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/operation_tracer.rb @@ -38,6 +38,7 @@ def initialize(otel_tracer, parent_tracer) @otel_tracer = otel_tracer @parent_tracer = parent_tracer @operation_names = {} + @operation_names_mutex = Mutex.new end # Trace a MongoDB operation. @@ -138,8 +139,8 @@ def handle_span_exception(span, exception) # The class-derived name is memoized per class: it is invariant and # deriving it (split + downcase) allocates on every call. The number # of operation classes is small and fixed, so the cache is unbounded - # by design; a benign race on first computation writes identical - # strings. + # by design. Access is synchronized: unsynchronized Hash mutation is + # not safe on all Ruby runtimes (e.g. JRuby). # # @param operation [ Mongo::Operation ] the operation. # @param op_name [ String | nil ] optional operation name. @@ -149,7 +150,9 @@ def operation_name(operation, op_name = nil) return op_name if op_name klass = operation.class - @operation_names[klass] ||= klass.name.split('::').last.downcase + @operation_names_mutex.synchronize do + @operation_names[klass] ||= klass.name.split('::').last.downcase + end end # Builds the attributes passed at span creation: the cheap set. The From e2e42530106b789c05e8db7f7d4be895aff6158d Mon Sep 17 00:00:00 2001 From: Dmitry Rybakov <160598371+comandeo-mongo@users.noreply.github.com> Date: Wed, 30 Sep 2026 13:29:38 +0200 Subject: [PATCH 08/11] RUBY-3952 Take server_connection_id from the command's own connection The command span read db.mongodb.server_connection_id from the server description, which comes from the monitoring connection's hello, not from the connection the command ran on. Since connection attributes are now cached per connection, that wrong value was also frozen for the connection's lifetime. Use the connection's own description, as command monitoring already does. --- lib/mongo/tracing/open_telemetry/command_tracer.rb | 2 +- spec/mongo/tracing/open_telemetry/command_tracer_spec.rb | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/mongo/tracing/open_telemetry/command_tracer.rb b/lib/mongo/tracing/open_telemetry/command_tracer.rb index 79bdb737f4..dfcaae3621 100644 --- a/lib/mongo/tracing/open_telemetry/command_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/command_tracer.rb @@ -202,7 +202,7 @@ def connection_attributes(connection) 'server.port' => connection.address.port, 'server.address' => connection.address.host, 'network.transport' => connection.transport.to_s, - 'db.mongodb.server_connection_id' => connection.server.description.server_connection_id, + 'db.mongodb.server_connection_id' => connection.description.server_connection_id, 'db.mongodb.driver_connection_id' => connection.id }.freeze connection.instance_variable_set(:@otel_connection_attributes, attrs) diff --git a/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb b/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb index e324202b6e..bc1c79a45a 100644 --- a/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb +++ b/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb @@ -18,9 +18,13 @@ id: 123, address: instance_double(Mongo::Address, host: 'localhost', port: 27_017), transport: :tcp, + # The connection's own description carries the id of this + # connection on the server; the server description comes + # from the monitoring connection and must not be used. + description: instance_double(Mongo::Server::Description, server_connection_id: 456), server: instance_double(Mongo::Server, description: instance_double(Mongo::Server::Description, - server_connection_id: 456))) + server_connection_id: 999))) end let(:message) do From 3bb7e5ebc279679afd6707fbd5e8fe9f4b1d8d07 Mon Sep 17 00:00:00 2001 From: Dmitry Rybakov <160598371+comandeo-mongo@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:31:57 +0100 Subject: [PATCH 09/11] RUBY-3952 Record no outcome on spans that are not recording The OpenTelemetry spec's performance guidelines now say that a span that is not recording is still made current but gets no outcome, and that a span with an invalid context gets no work at all. Error attributes, exceptions, the error status and the reply's cursor id were still recorded on non-recording spans, and invalid spans were still finished because the early return ran inside the method's rescue and ensure. Move the span work into a helper so that an invalid context returns before it, and gate the outcome on recording?. --- .../tracing/open_telemetry/command_tracer.rb | 61 +++++++++++-------- .../open_telemetry/operation_tracer.rb | 56 ++++++++++------- .../open_telemetry/command_tracer_spec.rb | 47 +++++++++++++- .../open_telemetry/operation_tracer_spec.rb | 38 +++++++++++- 4 files changed, 152 insertions(+), 50 deletions(-) diff --git a/lib/mongo/tracing/open_telemetry/command_tracer.rb b/lib/mongo/tracing/open_telemetry/command_tracer.rb index dfcaae3621..08c84f5bb2 100644 --- a/lib/mongo/tracing/open_telemetry/command_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/command_tracer.rb @@ -69,8 +69,7 @@ def start_span(message, operation_context, connection); end # @yield the block representing the command to be traced. # # @return [ Object ] the result of the command. - # rubocop:disable Lint/RescueException - def trace_command(message, _operation_context, connection) + def trace_command(message, _operation_context, connection, &block) # The command document and name are extracted once and threaded # through: the extraction helpers below allocate on every call. doc = message.documents.first @@ -83,30 +82,48 @@ def trace_command(message, _operation_context, connection) span = create_command_span(name, doc, connection) # An invalid context has no trace identity: it cannot be propagated, # continued, or correlated with anything downstream, so every - # operation on it is waste. This is a state check on the span we - # were handed, not detection of whether the SDK is available — a - # custom API-only provider returning real spans sees the full path. - # Must not key on recording?: an unsampled-but-valid context still - # has to be made current for propagation. + # operation on it, including finishing it, is waste. This is a state + # check on the span we were handed, not detection of whether the SDK + # is available — a custom API-only provider returning real spans + # sees the full path. Must not key on recording?: an + # unsampled-but-valid context still has to be made current for + # propagation. return yield unless span.context.valid? - cursor = cursor_id(name, doc) - apply_deferred_attributes(span, message, name, doc, cursor) if span.recording? - ::OpenTelemetry::Trace.with_span(span) do |s, c| + trace_with_span(span, message, name, doc, &block) + end + + private + + # Runs the command with the span made current. A span that is not + # recording is still made current, so that its context is propagated, + # but gets no further attributes and no outcome: the SDK would + # discard them. + # + # @param span [ OpenTelemetry::Trace::Span ] a span with a valid context. + # @param message [ Mongo::Protocol::Message ] the command message. + # @param name [ String ] the command name. + # @param doc [ Hash ] the command document. + # + # @return [ Object ] the result of the command. + # + # rubocop:disable Lint/RescueException + def trace_with_span(span, message, name, doc) + recording = span.recording? + apply_deferred_attributes(span, message, name, doc, cursor_id(name, doc)) if recording + ::OpenTelemetry::Trace.with_span(span) do |s, _c| yield.tap do |result| - process_command_result(result, cursor, c, s) + process_command_result(result, s) if recording end end rescue Exception => e - handle_command_exception(span, e) + handle_command_exception(span, e) if recording raise e ensure - span&.finish + span.finish end # rubocop:enable Lint/RescueException - private - # Determines whether the command must not be traced. Sensitive auth # commands carry credentials in their payloads (SCRAM proofs, cleartext # passwords, etc.) and the OpenTelemetry spec requires drivers to skip @@ -141,21 +158,17 @@ def create_command_span(name, doc, connection) # Processes the command result and updates span attributes. # # @param result [ Object ] the command result. - # @param cursor_id [ Integer | nil ] the cursor ID. - # @param context [ OpenTelemetry::Context ] the context. # @param span [ OpenTelemetry::Trace::Span ] the current span. - def process_command_result(result, cursor_id, context, span) - process_cursor_context(result, cursor_id, context, span) + def process_command_result(result, span) + process_cursor_context(result, span) maybe_trace_error(result, span) end # Handles exceptions that occur during command execution. # - # @param span [ OpenTelemetry::Trace::Span | nil ] the span. + # @param span [ OpenTelemetry::Trace::Span ] the span. # @param exception [ Exception ] the exception that occurred. def handle_command_exception(span, exception) - return unless span - if exception.is_a?(Mongo::Error::OperationFailure) span.set_attribute('db.response.status_code', exception.code.to_s) end @@ -240,10 +253,8 @@ def apply_deferred_attributes(span, message, name, doc, cursor) # Processes cursor context from the command result. # # @param result [ Object ] the command result. - # @param _cursor_id [ Integer | nil ] the cursor ID (unused). - # @param _context [ OpenTelemetry::Context ] the context (unused). # @param span [ OpenTelemetry::Trace::Span ] the current span. - def process_cursor_context(result, _cursor_id, _context, span) + def process_cursor_context(result, span) cursor_id = normalize_cursor_id(result.cursor_id) return unless cursor_id.positive? diff --git a/lib/mongo/tracing/open_telemetry/operation_tracer.rb b/lib/mongo/tracing/open_telemetry/operation_tracer.rb index 4a9b91db5b..f9999858c9 100644 --- a/lib/mongo/tracing/open_telemetry/operation_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/operation_tracer.rb @@ -55,35 +55,49 @@ def initialize(otel_tracer, parent_tracer) # @yield the block representing the operation to be traced. # # @return [ Object ] the result of the operation. - # - # rubocop:disable Lint/RescueException def trace_operation(operation, operation_context, op_name: nil, &block) span = create_operation_span(operation, operation_context, op_name) # An invalid context has no trace identity: it cannot be propagated, # continued, or correlated with anything downstream, so every - # operation on it is waste. This is a state check on the span we - # were handed, not detection of whether the SDK is available — a - # custom API-only provider returning real spans sees the full path. - # Must not key on recording?: an unsampled-but-valid context still - # has to be made current for propagation. Skipping here also leaves - # the cursor context map untouched, consistent with tracing being - # effectively off. + # operation on it, including finishing it, is waste. This is a state + # check on the span we were handed, not detection of whether the SDK + # is available — a custom API-only provider returning real spans + # sees the full path. Must not key on recording?: an + # unsampled-but-valid context still has to be made current for + # propagation. Skipping here also leaves the cursor context map + # untouched, consistent with tracing being effectively off. return yield unless span.context.valid? - if span.recording? && !operation.cursor_id.nil? + trace_with_span(span, operation, &block) + end + + private + + # Runs the operation with the span made current. A span that is not + # recording is still made current, so that the command spans created + # within it are nested under it, but gets no further attributes and + # no outcome: the SDK would discard them. + # + # @param span [ OpenTelemetry::Trace::Span ] a span with a valid context. + # @param operation [ Mongo::Operation ] the operation. + # + # @return [ Object ] the result of the operation. + # + # rubocop:disable Lint/RescueException + def trace_with_span(span, operation, &block) + recording = span.recording? + if recording && !operation.cursor_id.nil? span.set_attribute('db.mongodb.cursor_id', operation.cursor_id) end - execute_with_span(span, operation, &block) + execute_with_span(span, operation, recording, &block) rescue Exception => e - handle_span_exception(span, e) + handle_span_exception(span, e) if recording raise e ensure - span&.finish + span.finish end # rubocop:enable Lint/RescueException - private - # Creates an OpenTelemetry span for the operation. The operation name, # collection name and span name are each computed once and reused # between the span name and the attributes. @@ -110,14 +124,15 @@ def create_operation_span(operation, operation_context, op_name) # # @param span [ OpenTelemetry::Trace::Span ] the span. # @param operation [ Mongo::Operation ] the operation. + # @param recording [ true | false ] whether the span is recording. # # @yield the block to execute. # # @return [ Object ] the result of the block. - def execute_with_span(span, operation) + def execute_with_span(span, operation, recording) ::OpenTelemetry::Trace.with_span(span) do |s, c| yield.tap do |result| - process_cursor_context(result, operation.cursor_id, c, s) + process_cursor_context(result, operation.cursor_id, c, s, recording) end end end @@ -127,8 +142,6 @@ def execute_with_span(span, operation) # @param span [ OpenTelemetry::Trace::Span ] the span. # @param exception [ Exception ] the exception. def handle_span_exception(span, exception) - return unless span - span.record_exception(exception) span.status = ::OpenTelemetry::Trace::Status.error( "Unhandled exception of type: #{exception.class}" @@ -186,7 +199,8 @@ def span_attributes(operation, name, span_name, coll_name) # @param cursor_id [ Integer | nil ] the cursor ID before the operation. # @param context [ OpenTelemetry::Context ] the OpenTelemetry context. # @param span [ OpenTelemetry::Trace::Span ] the current span. - def process_cursor_context(result, cursor_id, context, span) + # @param recording [ true | false ] whether the span is recording. + def process_cursor_context(result, cursor_id, context, span, recording = true) return unless result.is_a?(Cursor) if result.id.zero? @@ -195,7 +209,7 @@ def process_cursor_context(result, cursor_id, context, span) elsif result.id && cursor_id.nil? # New cursor created, store its context. cursor_context_map[result.id] = context - span.set_attribute('db.mongodb.cursor_id', result.id) + span.set_attribute('db.mongodb.cursor_id', result.id) if recording end end diff --git a/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb b/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb index bc1c79a45a..7d09d89847 100644 --- a/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb +++ b/spec/mongo/tracing/open_telemetry/command_tracer_spec.rb @@ -135,6 +135,41 @@ expect(span).not_to receive(:set_attribute) command_tracer.trace_command(message, operation_context, connection) { result } end + + it 'still makes the span current, so that its context is propagated' do + expect(OpenTelemetry::Trace).to receive(:with_span).with(span).and_yield(span, context) + command_tracer.trace_command(message, operation_context, connection) { result } + end + + it 'does not record the cursor id from the reply' do + reply = instance_double(Mongo::Operation::Result, cursor_id: 789, successful?: true) + expect(span).not_to receive(:set_attribute) + command_tracer.trace_command(message, operation_context, connection) { reply } + end + + it 'does not record a failed reply' do + error = Mongo::Error::OperationFailure.new('error', nil, code: 42) + reply = instance_double(Mongo::Operation::Result, cursor_id: 0, successful?: false, error: error) + allow(reply).to receive(:validate!).and_raise(error) + expect(span).not_to receive(:set_attribute) + expect(span).not_to receive(:record_exception) + command_tracer.trace_command(message, operation_context, connection) { reply } + end + + it 'does not record a raised exception' do + error = Mongo::Error::OperationFailure.new('error', nil, code: 42) + expect(span).not_to receive(:set_attribute) + expect(span).not_to receive(:record_exception) + expect(span).not_to receive(:status=) + expect do + command_tracer.trace_command(message, operation_context, connection) { raise error } + end.to raise_error(error) + end + + it 'finishes the span' do + expect(span).to receive(:finish) + command_tracer.trace_command(message, operation_context, connection) { result } + end end it 'memoizes connection attributes per connection' do @@ -184,11 +219,19 @@ expect(return_value).to eq(:done) end - it 'finishes the span' do - expect(invalid_span).to receive(:finish) + it 'does not finish the span' do + expect(invalid_span).not_to receive(:finish) command_tracer.trace_command(message, operation_context, connection) { result } end + it 'does not record a raised exception' do + error = StandardError.new('generic error') + expect(invalid_span).not_to receive(:record_exception) + expect do + command_tracer.trace_command(message, operation_context, connection) { raise error } + end.to raise_error(error) + end + # Guards against an opentelemetry-api upgrade changing no-SDK semantics. # If this fails, re-evaluate the short-circuit: it degrades to a no-op, # correctness is unaffected. diff --git a/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb b/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb index d29c584856..72393dcb9d 100644 --- a/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb +++ b/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb @@ -125,6 +125,32 @@ expect(span).not_to receive(:set_attribute) operation_tracer.trace_operation(operation, operation_context) { result } end + + it 'still makes the span current, so that commands nest under it' do + expect(OpenTelemetry::Trace).to receive(:with_span).with(span).and_yield(span, context) + operation_tracer.trace_operation(operation, operation_context) { result } + end + + it 'does not record the cursor id of a new cursor' do + cursor = instance_double(Mongo::Cursor, id: 12_345) + allow(cursor).to receive(:is_a?).with(Mongo::Cursor).and_return(true) + expect(span).not_to receive(:set_attribute) + operation_tracer.trace_operation(operation, operation_context) { cursor } + end + + it 'does not record a raised exception' do + error = StandardError.new('test error') + expect(span).not_to receive(:record_exception) + expect(span).not_to receive(:status=) + expect do + operation_tracer.trace_operation(operation, operation_context) { raise error } + end.to raise_error(error) + end + + it 'finishes the span' do + expect(span).to receive(:finish) + operation_tracer.trace_operation(operation, operation_context) { result } + end end context 'with an invalid span (no SDK installed)' do @@ -149,10 +175,18 @@ expect(cursor_context_map).to be_empty end - it 'finishes the span' do - expect(invalid_span).to receive(:finish) + it 'does not finish the span' do + expect(invalid_span).not_to receive(:finish) operation_tracer.trace_operation(operation, operation_context) { result } end + + it 'does not record a raised exception' do + error = StandardError.new('test error') + expect(invalid_span).not_to receive(:record_exception) + expect do + operation_tracer.trace_operation(operation, operation_context) { raise error } + end.to raise_error(error) + end end context 'with custom operation name' do From c7295b381aad2e5af5cabb90f21a4d69f79e6911 Mon Sep 17 00:00:00 2001 From: Dmitry Rybakov <160598371+comandeo-mongo@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:32:19 +0100 Subject: [PATCH 10/11] RUBY-3952 Align tracer comments with the OpenTelemetry spec's guidelines --- .../tracing/open_telemetry/command_tracer.rb | 20 +++++++++---------- .../open_telemetry/operation_tracer.rb | 6 ++++-- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/lib/mongo/tracing/open_telemetry/command_tracer.rb b/lib/mongo/tracing/open_telemetry/command_tracer.rb index 08c84f5bb2..1002d7203d 100644 --- a/lib/mongo/tracing/open_telemetry/command_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/command_tracer.rb @@ -176,12 +176,12 @@ def handle_command_exception(span, exception) span.status = ::OpenTelemetry::Trace::Status.error("Unhandled exception of type: #{exception.class}") end - # Builds the attributes passed at span creation: the cheap, - # sampler-plausible set. Expensive attributes are deferred to - # apply_deferred_attributes — building them here would defeat the - # sampler's purpose, and on a non-recording span they would be - # discarded anyway. Keys whose value is nil are omitted rather than - # compacted afterwards, so the common case allocates nothing extra. + # Builds the attributes passed at span creation: the cheap set the + # OpenTelemetry spec recommends. These are built for every span, + # recorded or not, and are the only ones the sampler sees. The rest + # are deferred to apply_deferred_attributes. Keys whose value is nil + # are omitted rather than compacted afterwards, so the common case + # allocates nothing extra. # # @param doc [ Hash ] the command document. # @param name [ String ] the command name. @@ -223,11 +223,11 @@ def connection_attributes(connection) attrs end - # Sets the expensive attributes after span creation. Only called for + # Sets the remaining attributes after span creation. Only called for # recording spans: on non-recording spans set_attribute discards. - # Note for reviewers: these attributes are invisible to the sampler, - # which only sees what is passed to start_span. The built-in samplers - # do not read attributes, and db.query.text is off by default. + # These attributes are invisible to the sampler, which only sees what + # is passed to start_span; only custom samplers keying on them are + # affected. # # @param span [ OpenTelemetry::Trace::Span ] the current span. # @param message [ Mongo::Protocol::Message ] the command message. diff --git a/lib/mongo/tracing/open_telemetry/operation_tracer.rb b/lib/mongo/tracing/open_telemetry/operation_tracer.rb index f9999858c9..1ee9f6a8b2 100644 --- a/lib/mongo/tracing/open_telemetry/operation_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/operation_tracer.rb @@ -169,9 +169,11 @@ def operation_name(operation, op_name = nil) end # Builds the attributes passed at span creation: the cheap set. The - # cursor id is deferred to trace_operation (behind recording?) — on a + # cursor id is deferred to trace_with_span (behind recording?) — on a # non-recording span set_attribute discards, and the sampler has no - # use for it. + # use for it. db.operation.summary is outside the spec's recommended + # creation set, but here it is the span name, which is built anyway, + # and an attribute passed at creation is cheaper than one set later. # # @param operation [ Mongo::Operation ] the operation. # @param name [ String ] the operation name. From a33d917f76052890fcb489307f14eaf570af9f0a Mon Sep 17 00:00:00 2001 From: Dmitry Rybakov <160598371+comandeo-mongo@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:29:28 +0100 Subject: [PATCH 11/11] RUBY-3952 Drop a duplicate constant and a defaulted recording flag CommandTracer includes Secure, which now defines the same HELLO_COMMANDS. process_cursor_context defaulted its recording flag to true, so a caller that left it out would record attributes on a span that is not recording. --- lib/mongo/tracing/open_telemetry/command_tracer.rb | 12 +++--------- lib/mongo/tracing/open_telemetry/operation_tracer.rb | 2 +- .../tracing/open_telemetry/operation_tracer_spec.rb | 2 +- 3 files changed, 5 insertions(+), 11 deletions(-) diff --git a/lib/mongo/tracing/open_telemetry/command_tracer.rb b/lib/mongo/tracing/open_telemetry/command_tracer.rb index 1002d7203d..9058a8bb75 100644 --- a/lib/mongo/tracing/open_telemetry/command_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/command_tracer.rb @@ -23,13 +23,6 @@ module OpenTelemetry class CommandTracer include Mongo::Monitoring::Event::Secure - # Commands for which a span MUST NOT be created. The OpenTelemetry spec - # requires drivers to skip command spans for sensitive commands listed in - # the Command Logging and Monitoring spec. We additionally skip hello / - # legacy hello in all forms — these are handshake/heartbeat traffic and - # would only add noise to traces. - HELLO_COMMANDS = %w[hello ismaster isMaster].freeze - # Upper bound of the lsid UUID memo cache (see #lsid). LSID_CACHE_MAX = 128 @@ -127,8 +120,9 @@ def trace_with_span(span, message, name, doc) # Determines whether the command must not be traced. Sensitive auth # commands carry credentials in their payloads (SCRAM proofs, cleartext # passwords, etc.) and the OpenTelemetry spec requires drivers to skip - # command spans for them. Hello / legacy hello are also skipped to keep - # handshake traffic out of traces. + # command spans for them. Hello / legacy hello in all forms + # (Secure::HELLO_COMMANDS) are also skipped to keep handshake traffic + # out of traces. # # @param doc [ Hash ] the command document. # @param name [ String ] the command name. diff --git a/lib/mongo/tracing/open_telemetry/operation_tracer.rb b/lib/mongo/tracing/open_telemetry/operation_tracer.rb index 1ee9f6a8b2..3f38cfd689 100644 --- a/lib/mongo/tracing/open_telemetry/operation_tracer.rb +++ b/lib/mongo/tracing/open_telemetry/operation_tracer.rb @@ -202,7 +202,7 @@ def span_attributes(operation, name, span_name, coll_name) # @param context [ OpenTelemetry::Context ] the OpenTelemetry context. # @param span [ OpenTelemetry::Trace::Span ] the current span. # @param recording [ true | false ] whether the span is recording. - def process_cursor_context(result, cursor_id, context, span, recording = true) + def process_cursor_context(result, cursor_id, context, span, recording) return unless result.is_a?(Cursor) if result.id.zero? diff --git a/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb b/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb index 72393dcb9d..655686830d 100644 --- a/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb +++ b/spec/mongo/tracing/open_telemetry/operation_tracer_spec.rb @@ -624,7 +624,7 @@ describe '#process_cursor_context' do subject(:process_result) do - operation_tracer.send(:process_cursor_context, result, cursor_id, context, span) + operation_tracer.send(:process_cursor_context, result, cursor_id, context, span, true) end # rubocop:disable RSpec/VerifiedDoubles