From 1ddb17a19708a1a14a9b5e26826765d1bc347cd4 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 12 Nov 2026 16:00:47 +0000 Subject: [PATCH 01/36] JAVA-5734 Emit command events inside the command span scope (sync and async) Open the command span scope before the started event and keep it open through the failed event on the sync path; on the async path wrap the event sender so each event is emitted inside a short-lived scope. SLF4J MDC bridges now see the command span on every command log line. Originally prototyped in 1dd48a2864 on nabil_otel_spring_poc_driver. --- .../connection/InternalStreamConnection.java | 35 +++-- .../TracingScopedCommandEventSender.java | 76 +++++++++ .../InternalStreamConnectionTracingTest.java | 148 ++++++++++++++++++ 3 files changed, 248 insertions(+), 11 deletions(-) create mode 100644 driver-core/src/main/com/mongodb/internal/connection/TracingScopedCommandEventSender.java diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java index bdeba4211a..3dcbb04393 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java @@ -452,6 +452,10 @@ private T sendAndReceiveInternal(final CommandMessage message, final Decoder final OperationContext operationContext) { CommandEventSender commandEventSender = new NoOpCommandEventSender(); Span tracingSpan = null; + // Single owner of the span and event sender until the message is handed off to the receive phase: + // any failure from span creation through sendCommandMessage ends the span exactly once and emits at + // most one failed event (LoggingCommandEventSender suppresses terminal events until the started event + // has completed, and Span.closeScope() is a no-op if no scope was opened). try (ByteBufferBsonOutput bsonOutput = new ByteBufferBsonOutput(this)) { tracingSpan = operationContext .getTracingManager() @@ -471,6 +475,13 @@ private T sendAndReceiveInternal(final CommandMessage message, final Decoder if (isLoggingCommandNeeded || isTracingCommandPayloadNeeded) { commandDocument = message.getCommandDocument(bsonOutput); } + if (isTracingCommandPayloadNeeded) { + tracingSpan.setQueryText(commandDocument); + } + // Open the scope before the started event so command listeners and logs observe the command span. + if (tracingSpan != null) { + tracingSpan.openScope(); + } if (isLoggingCommandNeeded) { commandEventSender = new LoggingCommandEventSender( SECURITY_SENSITIVE_COMMANDS, SECURITY_SENSITIVE_HELLO_COMMANDS, description, commandListener, @@ -478,20 +489,18 @@ private T sendAndReceiveInternal(final CommandMessage message, final Decoder COMMAND_PROTOCOL_LOGGER, loggerSettings); commandEventSender.sendStartedEvent(); } - if (isTracingCommandPayloadNeeded) { - tracingSpan.setQueryText(commandDocument); - } - if (tracingSpan != null) { - tracingSpan.openScope(); - } sendCommandMessage(message, bsonOutput, operationContext); } catch (Throwable t) { - if (tracingSpan != null) { - tracingSpan.error(t); - tracingSpan.closeScope(); - tracingSpan.end(); + // Emit the failed event while the span scope is still open so the log/listener see the command span. + try { + commandEventSender.sendFailedEvent(t); + } finally { + if (tracingSpan != null) { + tracingSpan.error(t); + tracingSpan.closeScope(); + tracingSpan.end(); + } } - commandEventSender.sendFailedEvent(t); throw t; } @@ -732,6 +741,10 @@ private void sendAndReceiveAsyncInternal(final CommandMessage message, final if (isTracingCommandPayloadNeeded) { tracingSpan.setQueryText(commandDocument); } + if (tracingSpan != null && isLoggingCommandNeeded) { + // The async path never holds a scope across callbacks; emit each event inside a short-lived one. + commandEventSender = new TracingScopedCommandEventSender(commandEventSender, tracingSpan); + } final Span commandSpan = tracingSpan; SingleResultCallback tracingCallback = commandSpan == null ? callback : (result, t) -> { diff --git a/driver-core/src/main/com/mongodb/internal/connection/TracingScopedCommandEventSender.java b/driver-core/src/main/com/mongodb/internal/connection/TracingScopedCommandEventSender.java new file mode 100644 index 0000000000..40d56ae8de --- /dev/null +++ b/driver-core/src/main/com/mongodb/internal/connection/TracingScopedCommandEventSender.java @@ -0,0 +1,76 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.connection; + +import com.mongodb.internal.observability.micrometer.Span; + +/** + * Emits command events while the command span's scope is open on the emitting thread, so that command + * listeners and log appenders observe the command span (for example as {@code traceId}/{@code spanId} in + * the MDC). The scope is opened and closed around each event; {@link Span#closeScope()} is idempotent. + * + *

This class is not part of the public API and may be removed or changed at any time

+ */ +final class TracingScopedCommandEventSender implements CommandEventSender { + private final CommandEventSender delegate; + private final Span span; + + TracingScopedCommandEventSender(final CommandEventSender delegate, final Span span) { + this.delegate = delegate; + this.span = span; + } + + @Override + public void sendStartedEvent() { + span.openScope(); + try { + delegate.sendStartedEvent(); + } finally { + span.closeScope(); + } + } + + @Override + public void sendFailedEvent(final Throwable t) { + span.openScope(); + try { + delegate.sendFailedEvent(t); + } finally { + span.closeScope(); + } + } + + @Override + public void sendSucceededEvent(final ResponseBuffers responseBuffers) { + span.openScope(); + try { + delegate.sendSucceededEvent(responseBuffers); + } finally { + span.closeScope(); + } + } + + @Override + public void sendSucceededEventForOneWayCommand() { + span.openScope(); + try { + delegate.sendSucceededEventForOneWayCommand(); + } finally { + span.closeScope(); + } + } +} diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java index e8d5c589e7..918be15b87 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java @@ -20,6 +20,10 @@ import com.mongodb.MongoNamespace; import com.mongodb.async.FutureResultCallback; import com.mongodb.connection.AsyncCompletionHandler; +import com.mongodb.event.CommandFailedEvent; +import com.mongodb.event.CommandListener; +import com.mongodb.event.CommandStartedEvent; +import com.mongodb.event.CommandSucceededEvent; import com.mongodb.internal.IgnorableRequestContext; import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.TimeoutSettings; @@ -42,6 +46,8 @@ import java.io.ByteArrayOutputStream; import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -250,6 +256,148 @@ void asyncUnacknowledgedSendAttachesTelemetrySectionAndEndsSpanOnce() { connection.close(); } + /** Records whether the command span scope was open on the emitting thread when each command event fired. */ + private static final class ScopeObservingListener implements CommandListener { + private final RecordingSpan span; + private final Map scopeOpenAtEvent = new ConcurrentHashMap<>(); + + ScopeObservingListener(final RecordingSpan span) { + this.span = span; + } + + private void record(final String event) { + scopeOpenAtEvent.put(event, span.openScopeCount.get() > span.closeScopeCount.get()); + } + + @Override + public void commandStarted(final CommandStartedEvent event) { + record("started"); + } + + @Override + public void commandSucceeded(final CommandSucceededEvent event) { + record("succeeded"); + } + + @Override + public void commandFailed(final CommandFailedEvent event) { + record("failed"); + } + } + + @Test + @DisplayName("Sync: started and succeeded command events fire while the command span scope is open") + void syncCommandEventsFireInsideSpanScope() { + AtomicInteger readCallCount = new AtomicInteger(); + CapturingTestStream stream = new CapturingTestStream() { + @Override + public ByteBuf read(final int numBytes, final OperationContext operationContext) { + return readCallCount.incrementAndGet() == 1 + ? createValidResponseHeader(getCommandMessageId()) + : createResponseBody(new BsonDocument("ok", new BsonInt32(1))); + } + }; + RecordingSpan span = new RecordingSpan(); + ScopeObservingListener listener = new ScopeObservingListener(span); + InternalStreamConnection connection = createOpenConnection(stream, listener); + CommandMessage commandMessage = createPingCommand(); + stream.setCommandMessageId(commandMessage.getId()); + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), createTracedOperationContext(span)); + assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("started"), "started event must see the span scope"); + assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("succeeded"), "succeeded event must see the span scope"); + assertEquals(span.openScopeCount.get(), span.closeScopeCount.get(), "scopes must be balanced"); + assertEquals(1, span.endCount.get()); + connection.close(); + } + + @Test + @DisplayName("Async: started and succeeded command events fire while the command span scope is open") + void asyncCommandEventsFireInsideSpanScope() { + AtomicInteger readAsyncCallCount = new AtomicInteger(); + CapturingTestStream stream = new CapturingTestStream() { + @Override + public void readAsync(final int numBytes, final OperationContext operationContext, + final AsyncCompletionHandler handler) { + handler.completed(readAsyncCallCount.incrementAndGet() == 1 + ? createValidResponseHeader(getCommandMessageId()) + : createResponseBody(new BsonDocument("ok", new BsonInt32(1)))); + } + }; + RecordingSpan span = new RecordingSpan(); + ScopeObservingListener listener = new ScopeObservingListener(span); + InternalStreamConnection connection = createOpenConnection(stream, listener); + CommandMessage commandMessage = createPingCommand(); + stream.setCommandMessageId(commandMessage.getId()); + FutureResultCallback callback = new FutureResultCallback<>(); + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), createTracedOperationContext(span), callback); + callback.get(5, TimeUnit.SECONDS); + assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("started"), "started event must see the span scope"); + assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("succeeded"), "succeeded event must see the span scope"); + assertEquals(span.openScopeCount.get(), span.closeScopeCount.get(), "scopes must be balanced"); + assertEquals(1, span.endCount.get()); + connection.close(); + } + + @Test + @DisplayName("Sync: failed command event fires inside the span scope when the write fails") + void syncFailedEventFiresInsideSpanScope() { + CapturingTestStream stream = new CapturingTestStream() { + @Override + public void write(final List buffers, final OperationContext operationContext) { + throw new RuntimeException("simulated write failure"); + } + }; + RecordingSpan span = new RecordingSpan(); + ScopeObservingListener listener = new ScopeObservingListener(span); + InternalStreamConnection connection = createOpenConnection(stream, listener); + assertThrows(MongoInternalException.class, + () -> connection.sendAndReceive(createPingCommand(), new BsonDocumentCodec(), createTracedOperationContext(span))); + assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("failed"), "failed event must see the span scope"); + assertEquals(span.openScopeCount.get(), span.closeScopeCount.get(), "scopes must be balanced"); + assertEquals(1, span.endCount.get()); + connection.close(); + } + + @Test + @DisplayName("Async: failed command event fires inside the span scope when the write fails") + void asyncFailedEventFiresInsideSpanScope() { + CapturingTestStream stream = new CapturingTestStream() { + @Override + public void writeAsync(final List buffers, final OperationContext operationContext, + final AsyncCompletionHandler handler) { + handler.failed(new RuntimeException("simulated async write failure")); + } + }; + RecordingSpan span = new RecordingSpan(); + ScopeObservingListener listener = new ScopeObservingListener(span); + InternalStreamConnection connection = createOpenConnection(stream, listener); + FutureResultCallback callback = new FutureResultCallback<>(); + connection.sendAndReceiveAsync(createPingCommand(), new BsonDocumentCodec(), createTracedOperationContext(span), callback); + assertThrows(RuntimeException.class, () -> callback.get(5, TimeUnit.SECONDS)); + assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("failed"), "failed event must see the span scope"); + assertEquals(span.openScopeCount.get(), span.closeScopeCount.get(), "scopes must be balanced"); + assertEquals(1, span.endCount.get()); + connection.close(); + } + + @Test + @DisplayName("Async: one-way (w:0) succeeded event fires inside the span scope") + void asyncOneWaySucceededEventFiresInsideSpanScope() { + CapturingTestStream stream = new CapturingTestStream() { + }; + RecordingSpan span = new RecordingSpan(); + ScopeObservingListener listener = new ScopeObservingListener(span); + InternalStreamConnection connection = createOpenConnection(stream, listener); + FutureResultCallback callback = new FutureResultCallback<>(); + connection.sendAndReceiveAsync(createUnacknowledgedInsertCommand(), new BsonDocumentCodec(), + createTracedOperationContext(span), callback); + assertNull(callback.get(5, TimeUnit.SECONDS)); + assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("succeeded"), "one-way succeeded event must see the span scope"); + assertEquals(span.openScopeCount.get(), span.closeScopeCount.get(), "scopes must be balanced"); + assertEquals(1, span.endCount.get()); + connection.close(); + } + private static CommandMessage createUnacknowledgedInsertCommand() { BsonDocument insert = new BsonDocument("insert", new BsonString("coll")) .append("documents", new BsonArray(singletonList(new BsonDocument("_id", new BsonInt32(1))))) From e1c6e7529608d29109be227d33a2786f6587b61f Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 12 Nov 2026 16:05:57 +0000 Subject: [PATCH 02/36] JAVA-5734 Allow MicrometerSpan scopes to nest Log emission sites will re-enter the operation span scope while the sync path already holds it; a single scope field would leak the outer scope on the inner close. --- .../micrometer/MicrometerTracer.java | 16 +++-- .../observability/micrometer/Span.java | 9 ++- .../micrometer/MicrometerSpanScopeTest.java | 68 +++++++++++++++++++ 3 files changed, 83 insertions(+), 10 deletions(-) create mode 100644 driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java index 00338928f5..5641e29aa7 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java @@ -32,6 +32,8 @@ import org.bson.json.JsonWriterSettings; import java.io.StringWriter; +import java.util.ArrayDeque; +import java.util.Deque; import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE; import static com.mongodb.internal.observability.micrometer.TracingManager.ENV_OBSERVABILITY_QUERY_TEXT_MAX_LENGTH; @@ -236,13 +238,13 @@ static String traceParent(final Observation observation) { /** * Represents a Micrometer-based span. */ - private static class MicrometerSpan implements Span { + // visible for testing + static class MicrometerSpan implements Span { private final Observation observation; @Nullable private final MongoNamespace namespace; private final int queryTextLength; - @Nullable - private Observation.Scope scope; + private final Deque scopes = new ArrayDeque<>(); /** * Constructs a new {@link MicrometerSpan} instance with an associated Observation and MongoDB namespace. @@ -258,15 +260,15 @@ private static class MicrometerSpan implements Span { } @Override - public void openScope() { - this.scope = observation.openScope(); + public synchronized void openScope() { + scopes.push(observation.openScope()); } @Override - public void closeScope() { + public synchronized void closeScope() { + Observation.Scope scope = scopes.poll(); if (scope != null) { scope.close(); - scope = null; } } diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java index f0821f2375..708d20c51a 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java @@ -91,13 +91,16 @@ public MongodbObservationContext getMongodbObservationContext() { /** * Opens a scope for this span, making it the current observation on the thread. * A successful {@code openScope()} must be followed by {@link #closeScope()}. + * Scopes nest: each {@code openScope()} may be paired with a {@link #closeScope()}, and calling + * {@code openScope()} after {@link #end()} does not throw. */ void openScope(); /** - * Closes the scope previously opened by {@link #openScope()}, restoring the previous observation. - * Calling this without a prior {@code openScope()}, or more than once, is a no-op — error-handling - * paths may therefore call it unconditionally. + * Closes the most recently opened scope for this span, restoring the previous observation. + * Scopes nest: each {@code closeScope()} closes the most recently opened scope, so an equal number + * of {@code openScope()} and {@code closeScope()} calls leaves no scope open. + * Calling this with no open scope is a no-op — error-handling paths may therefore call it unconditionally. */ void closeScope(); diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java new file mode 100644 index 0000000000..e3604f085e --- /dev/null +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.observability.micrometer; + +import io.micrometer.observation.Observation; +import io.micrometer.observation.ObservationRegistry; +import io.micrometer.observation.tck.TestObservationRegistry; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +class MicrometerSpanScopeTest { + + @Test + void nestedOpenAndCloseRestoreTheOuterScope() { + TestObservationRegistry registry = TestObservationRegistry.create(); + Observation observation = Observation.start("op", registry); + Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); + + span.openScope(); // outer, e.g. MongoClusterImpl + assertSame(observation, registry.getCurrentObservation()); + span.openScope(); // inner, e.g. DefaultConnectionPool at log time + assertSame(observation, registry.getCurrentObservation()); + span.closeScope(); // inner close + assertSame(observation, registry.getCurrentObservation(), "outer scope must still be current"); + span.closeScope(); // outer close + assertNull(registry.getCurrentObservation(), "no scope may remain after balanced closes"); + observation.stop(); + } + + @Test + void openScopeAfterEndDoesNotThrow() { + ObservationRegistry registry = TestObservationRegistry.create(); + Observation observation = Observation.start("op", registry); + Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); + span.end(); + assertDoesNotThrow(span::openScope); + assertDoesNotThrow(span::closeScope); + } + + @Test + void extraCloseIsNoOp() { + ObservationRegistry registry = TestObservationRegistry.create(); + Observation observation = Observation.start("op", registry); + Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); + span.closeScope(); + span.openScope(); + span.closeScope(); + assertDoesNotThrow(span::closeScope); + observation.stop(); + } +} From 0ada3b6b0d5821bc8f13dcce4add41db872a2666 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 12 Nov 2026 16:24:25 +0000 Subject: [PATCH 03/36] JAVA-5734 Track MicrometerSpan scopes per thread A shared per-span deque corrupts thread-locals when two threads interleave open/close on the same span (reactive operation spans are used from Netty and cluster threads): closing another thread's scope restores the wrong previous observation on the wrong thread. Every caller pairs open and close on the same thread, so keep one LIFO stack per thread and drop the span-wide lock. --- driver-core/build.gradle.kts | 1 + .../micrometer/MicrometerTracer.java | 10 +-- .../observability/micrometer/Span.java | 18 ++--- .../micrometer/MicrometerSpanScopeTest.java | 66 +++++++++++++++++++ gradle/libs.versions.toml | 1 + 5 files changed, 83 insertions(+), 13 deletions(-) diff --git a/driver-core/build.gradle.kts b/driver-core/build.gradle.kts index ff67aa67d5..5dfe4f1732 100644 --- a/driver-core/build.gradle.kts +++ b/driver-core/build.gradle.kts @@ -63,6 +63,7 @@ dependencies { testImplementation(libs.reflections) // Tracing testing + testImplementation(libs.micrometer.observation.test) testImplementation(platform(libs.micrometer.tracing.integration.test.bom)) testImplementation(libs.micrometer.tracing.integration.test) { exclude(group = "org.junit.jupiter") } diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java index 5641e29aa7..f7b3283e46 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java @@ -244,7 +244,7 @@ static class MicrometerSpan implements Span { @Nullable private final MongoNamespace namespace; private final int queryTextLength; - private final Deque scopes = new ArrayDeque<>(); + private final ThreadLocal> scopes = ThreadLocal.withInitial(ArrayDeque::new); /** * Constructs a new {@link MicrometerSpan} instance with an associated Observation and MongoDB namespace. @@ -260,13 +260,13 @@ static class MicrometerSpan implements Span { } @Override - public synchronized void openScope() { - scopes.push(observation.openScope()); + public void openScope() { + scopes.get().push(observation.openScope()); } @Override - public synchronized void closeScope() { - Observation.Scope scope = scopes.poll(); + public void closeScope() { + Observation.Scope scope = scopes.get().poll(); if (scope != null) { scope.close(); } diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java index 708d20c51a..69da7633ad 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java @@ -89,18 +89,20 @@ public MongodbObservationContext getMongodbObservationContext() { }; /** - * Opens a scope for this span, making it the current observation on the thread. - * A successful {@code openScope()} must be followed by {@link #closeScope()}. - * Scopes nest: each {@code openScope()} may be paired with a {@link #closeScope()}, and calling - * {@code openScope()} after {@link #end()} does not throw. + * Opens a scope for this span, making it the current observation on the calling thread. + * A successful {@code openScope()} must be followed by a {@link #closeScope()} on the same thread. + * Scopes nest per thread: each {@code openScope()} may be paired with a {@link #closeScope()} + * on the same thread, and calling {@code openScope()} after {@link #end()} does not throw. */ void openScope(); /** - * Closes the most recently opened scope for this span, restoring the previous observation. - * Scopes nest: each {@code closeScope()} closes the most recently opened scope, so an equal number - * of {@code openScope()} and {@code closeScope()} calls leaves no scope open. - * Calling this with no open scope is a no-op — error-handling paths may therefore call it unconditionally. + * Closes the most recently opened scope for this span on the calling thread, restoring the + * previous observation. Each {@code closeScope()} must be called on the same thread as its + * matching {@code openScope()}; scopes nest per thread, and an equal number of + * {@code openScope()} and {@code closeScope()} calls on a thread leaves no scope open on it. + * Calling this with no open scope on the calling thread is a no-op — error-handling paths may + * therefore call it unconditionally. */ void closeScope(); diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java index e3604f085e..f94092b369 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java @@ -21,6 +21,9 @@ import io.micrometer.observation.tck.TestObservationRegistry; import org.junit.jupiter.api.Test; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; @@ -35,10 +38,12 @@ void nestedOpenAndCloseRestoreTheOuterScope() { span.openScope(); // outer, e.g. MongoClusterImpl assertSame(observation, registry.getCurrentObservation()); + Observation.Scope outerScope = registry.getCurrentObservationScope(); span.openScope(); // inner, e.g. DefaultConnectionPool at log time assertSame(observation, registry.getCurrentObservation()); span.closeScope(); // inner close assertSame(observation, registry.getCurrentObservation(), "outer scope must still be current"); + assertSame(outerScope, registry.getCurrentObservationScope(), "the outer scope itself must be current"); span.closeScope(); // outer close assertNull(registry.getCurrentObservation(), "no scope may remain after balanced closes"); observation.stop(); @@ -54,6 +59,67 @@ void openScopeAfterEndDoesNotThrow() { assertDoesNotThrow(span::closeScope); } + @Test + void scopesOpenedOnDifferentThreadsAreIndependent() throws Exception { + TestObservationRegistry registry = TestObservationRegistry.create(); + Observation observation = Observation.start("op", registry); + Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); + + span.openScope(); // thread A (this thread) opens the scope + assertSame(observation, registry.getCurrentObservation()); + + ExecutorService threadB = Executors.newSingleThreadExecutor(); + try { + threadB.submit(() -> { + span.openScope(); // thread B opens its own scope on the same span + span.closeScope(); // and closes it again + assertNull(registry.getCurrentObservation(), "thread B leaves no scope open on its thread"); + }).get(); // surface thread B's failures on this thread + } finally { + threadB.shutdown(); + } + + assertSame(observation, registry.getCurrentObservation(), + "thread A's scope must survive thread B's open/close"); + span.closeScope(); // thread A closes its scope + assertNull(registry.getCurrentObservation(), "no scope may remain after balanced closes"); + observation.stop(); + } + + @Test + void aThreadsCloseDoesNotCloseAnotherThreadsScope() throws Exception { + TestObservationRegistry registry = TestObservationRegistry.create(); + Observation outer = Observation.start("outer", registry); + Observation observation = Observation.start("op", registry); + Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); + + Observation.Scope outerScope = outer.openScope(); // thread A already has an outer observation current + span.openScope(); // thread A opens the span scope; its previous observation is outer + assertSame(observation, registry.getCurrentObservation()); + + ExecutorService threadB = Executors.newSingleThreadExecutor(); + try { + threadB.submit(() -> span.openScope()).get(); // thread B opens its own scope and keeps it open + + span.closeScope(); // thread A closes while thread B's scope is still open + assertSame(outer, registry.getCurrentObservation(), + "thread A's close must restore thread A's previous observation"); + + threadB.submit(() -> { + assertSame(observation, registry.getCurrentObservation(), + "thread B's scope must still be open"); + span.closeScope(); + assertNull(registry.getCurrentObservation(), "thread B leaves no scope open on its thread"); + }).get(); + } finally { + threadB.shutdown(); + } + outerScope.close(); + assertNull(registry.getCurrentObservation(), "thread A leaves no scope open on its thread"); + outer.stop(); + observation.stop(); + } + @Test void extraCloseIsNoOp() { ObservationRegistry registry = TestObservationRegistry.create(); diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 7ff2f38a87..73adf60f34 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -99,6 +99,7 @@ snappy-java = { module = "org.xerial.snappy:snappy-java", version.ref = "snappy" zstd-jni = { module = "com.github.luben:zstd-jni", version.ref = "zstd" } micrometer-observation-bom = { module = "io.micrometer:micrometer-bom", version.ref = "micrometer-observation-bom" } micrometer-observation = { module = "io.micrometer:micrometer-observation" } +micrometer-observation-test = { module = "io.micrometer:micrometer-observation-test" } graal-sdk = { module = "org.graalvm.sdk:graal-sdk", version.ref = "graal-sdk" } graal-sdk-nativeimage = { module = "org.graalvm.sdk:nativeimage", version.ref = "graal-sdk" } From 45a04053c22eb9bd95ef78ddde73d54ba81abcf9 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 12 Nov 2026 16:28:31 +0000 Subject: [PATCH 04/36] JAVA-5734 Add SpanScopes.runInScope helper --- .../observability/micrometer/SpanScopes.java | 48 ++++++++++++ .../micrometer/SpanScopesTest.java | 75 +++++++++++++++++++ 2 files changed, 123 insertions(+) create mode 100644 driver-core/src/main/com/mongodb/internal/observability/micrometer/SpanScopes.java create mode 100644 driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanScopesTest.java diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/SpanScopes.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/SpanScopes.java new file mode 100644 index 0000000000..a9c3149c2c --- /dev/null +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/SpanScopes.java @@ -0,0 +1,48 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.observability.micrometer; + +import com.mongodb.lang.Nullable; + +/** + * Runs an action while a {@link Span}'s scope is open on the current thread, so that anything that reads the + * current tracing context during the action (log appenders, MDC bridges, listeners) observes that span. + * + *

This class is not part of the public API and may be removed or changed at any time

+ */ +public final class SpanScopes { + + /** + * @param span the span to make current, or {@code null} to run the action without touching any scope + * @param action the action to run + */ + public static void runInScope(@Nullable final Span span, final Runnable action) { + if (span == null) { + action.run(); + return; + } + span.openScope(); + try { + action.run(); + } finally { + span.closeScope(); + } + } + + private SpanScopes() { + } +} diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanScopesTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanScopesTest.java new file mode 100644 index 0000000000..2f8da85f3f --- /dev/null +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanScopesTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.observability.micrometer; + +import com.mongodb.MongoNamespace; +import com.mongodb.lang.Nullable; +import com.mongodb.observability.micrometer.MongodbObservationContext; +import org.bson.BsonDocument; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static java.util.Arrays.asList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class SpanScopesTest { + + @Test + void runsActionDirectlyWhenSpanIsNull() { + List calls = new ArrayList<>(); + SpanScopes.runInScope(null, () -> calls.add("action")); + assertEquals(asList("action"), calls); + } + + @Test + void opensScopeBeforeActionAndClosesAfter() { + List calls = new ArrayList<>(); + SpanScopes.runInScope(new RecordingSpan(calls), () -> calls.add("action")); + assertEquals(asList("open", "action", "close"), calls); + } + + @Test + void closesScopeWhenActionThrows() { + List calls = new ArrayList<>(); + RuntimeException failure = new RuntimeException("appender failed"); + RuntimeException thrown = assertThrows(RuntimeException.class, + () -> SpanScopes.runInScope(new RecordingSpan(calls), () -> { throw failure; })); + assertEquals(failure, thrown); + assertEquals(asList("open", "close"), calls); + } + + static final class RecordingSpan implements Span { + private final List calls; + + RecordingSpan(final List calls) { + this.calls = calls; + } + + @Override public void openScope() { calls.add("open"); } + @Override public void closeScope() { calls.add("close"); } + @Override public void setQueryText(final BsonDocument commandDocument) { } + @Override public void event(final String event) { } + @Override public void error(final Throwable throwable) { } + @Override public void end() { } + @Override public TraceContext context() { return TraceContext.EMPTY; } + @Override @Nullable public MongodbObservationContext getMongodbObservationContext() { return null; } + @Override @Nullable public MongoNamespace getNamespace() { return null; } + } +} From 3f5ce4cd091e172d25292d3cbe657f1f8e81eec1 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 12 Nov 2026 16:31:31 +0000 Subject: [PATCH 05/36] JAVA-5734 Emit server selection log messages inside the operation span scope --- .../internal/connection/BaseCluster.java | 25 +-- .../connection/BaseClusterLogScopeTest.java | 145 ++++++++++++++++++ 2 files changed, 160 insertions(+), 10 deletions(-) create mode 100644 driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java diff --git a/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java b/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java index e9dfccc338..91f6a8ed74 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java +++ b/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java @@ -41,6 +41,7 @@ import com.mongodb.internal.logging.LogMessage; import com.mongodb.internal.logging.LogMessage.Entry; import com.mongodb.internal.logging.StructuredLogger; +import com.mongodb.internal.observability.micrometer.SpanScopes; import com.mongodb.internal.selector.AtMostTwoRandomServerSelector; import com.mongodb.internal.selector.LatencyMinimizingServerSelector; import com.mongodb.internal.selector.MinimumOperationCountServerSelector; @@ -555,25 +556,26 @@ static void logServerSelectionStarted( final ServerSelector serverSelector, final ClusterDescription clusterDescription) { if (STRUCTURED_LOGGER.isRequired(DEBUG, clusterId)) { - STRUCTURED_LOGGER.log(new LogMessage( + LogMessage logMessage = new LogMessage( SERVER_SELECTION, DEBUG, "Server selection started", clusterId, asList( new Entry(OPERATION, operationContext.getOperationName()), new Entry(OPERATION_ID, operationContext.getId()), new Entry(SELECTOR, serverSelector.toString()), new Entry(TOPOLOGY_DESCRIPTION, clusterDescription.getShortDescription())), - "Server selection started for operation[ {}] with ID {}. Selector: {}, topology description: {}")); + "Server selection started for operation[ {}] with ID {}. Selector: {}, topology description: {}"); + SpanScopes.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); } } - private static void logServerSelectionWaiting( + static void logServerSelectionWaiting( final OperationContext operationContext, final ClusterId clusterId, final Timeout timeout, final ServerSelector serverSelector, final ClusterDescription clusterDescription) { if (STRUCTURED_LOGGER.isRequired(INFO, clusterId)) { - STRUCTURED_LOGGER.log(new LogMessage( + LogMessage logMessage = new LogMessage( SERVER_SELECTION, INFO, "Waiting for suitable server to become available", clusterId, asList( new Entry(OPERATION, operationContext.getOperationName()), @@ -585,11 +587,12 @@ private static void logServerSelectionWaiting( new Entry(SELECTOR, serverSelector.toString()), new Entry(TOPOLOGY_DESCRIPTION, clusterDescription.getShortDescription())), "Waiting for server to become available for operation[ {}] with ID {}.[ Remaining time: {} ms.]" - + " Selector: {}, topology description: {}.")); + + " Selector: {}, topology description: {}."); + SpanScopes.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); } } - private static void logServerSelectionFailed( + static void logServerSelectionFailed( final OperationContext operationContext, final ClusterId clusterId, final MongoException failure, @@ -602,7 +605,7 @@ private static void logServerSelectionFailed( // The logging spec requires us to avoid such duplication of information. ? MongoTimeoutException.class.getName() + ": Timed out while waiting for a suitable server" : failure.toString(); - STRUCTURED_LOGGER.log(new LogMessage( + LogMessage logMessage = new LogMessage( SERVER_SELECTION, DEBUG, "Server selection failed", clusterId, asList( new Entry(OPERATION, operationContext.getOperationName()), @@ -610,7 +613,8 @@ private static void logServerSelectionFailed( new Entry(FAILURE, failureDescription), new Entry(SELECTOR, serverSelector.toString()), new Entry(TOPOLOGY_DESCRIPTION, clusterDescription.getShortDescription())), - "Server selection failed for operation[ {}] with ID {}. Failure: {}. Selector: {}, topology description: {}")); + "Server selection failed for operation[ {}] with ID {}. Failure: {}. Selector: {}, topology description: {}"); + SpanScopes.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); } } @@ -621,7 +625,7 @@ static void logServerSelectionSucceeded( final ServerSelector serverSelector, final ClusterDescription clusterDescription) { if (STRUCTURED_LOGGER.isRequired(DEBUG, clusterId)) { - STRUCTURED_LOGGER.log(new LogMessage( + LogMessage logMessage = new LogMessage( SERVER_SELECTION, DEBUG, "Server selection succeeded", clusterId, asList( new Entry(OPERATION, operationContext.getOperationName()), @@ -631,7 +635,8 @@ static void logServerSelectionSucceeded( new Entry(SELECTOR, serverSelector.toString()), new Entry(TOPOLOGY_DESCRIPTION, clusterDescription.getShortDescription())), "Server selection succeeded for operation[ {}] with ID {}. Selected server: {}[:{}]." - + " Selector: {}, topology description: {}")); + + " Selector: {}, topology description: {}"); + SpanScopes.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java new file mode 100644 index 0000000000..25a2ad7f14 --- /dev/null +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java @@ -0,0 +1,145 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.connection; + +import com.mongodb.MongoTimeoutException; +import com.mongodb.MongoNamespace; +import com.mongodb.ServerAddress; +import com.mongodb.connection.ClusterDescription; +import com.mongodb.connection.ClusterId; +import com.mongodb.connection.ServerDescription; +import com.mongodb.internal.logging.LogMessage; +import com.mongodb.internal.observability.micrometer.Span; +import com.mongodb.internal.observability.micrometer.TraceContext; +import com.mongodb.internal.selector.ReadPreferenceServerSelector; +import com.mongodb.lang.Nullable; +import com.mongodb.logging.TestLoggingInterceptor; +import com.mongodb.observability.micrometer.MongodbObservationContext; +import org.bson.BsonDocument; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; + +import static com.mongodb.ClusterFixture.createOperationContext; +import static com.mongodb.ReadPreference.primary; +import static com.mongodb.connection.ClusterConnectionMode.SINGLE; +import static com.mongodb.connection.ClusterType.STANDALONE; +import static com.mongodb.internal.logging.LogMessage.Component.SERVER_SELECTION; +import static com.mongodb.internal.logging.LogMessage.Level.DEBUG; +import static org.junit.jupiter.api.Assertions.assertEquals; + +final class BaseClusterLogScopeTest { + + /** Records, per log message id, whether the span scope was open on the thread that emitted it. */ + private static final class ScopeRecordingInterceptor extends TestLoggingInterceptor { + private final ScopeCountingSpan span; + private final Map scopeOpenAtMessage = new ConcurrentHashMap<>(); + + ScopeRecordingInterceptor(final String applicationName, final ScopeCountingSpan span) { + super(applicationName, new LoggingFilter(Collections.singletonMap(SERVER_SELECTION, DEBUG))); + this.span = span; + } + + @Override + public synchronized void intercept(final LogMessage message) { + super.intercept(message); + scopeOpenAtMessage.put(message.getMessageId(), span.isScopeOpen()); + } + } + + @Test + void serverSelectionMessagesAreEmittedInsideTheOperationSpanScope() { + String applicationName = "BaseClusterLogScopeTest"; + ClusterId clusterId = new ClusterId(applicationName); + ScopeCountingSpan span = new ScopeCountingSpan(); + OperationContext operationContext = createOperationContext(); + operationContext.setTracingSpan(span); + ServerAddress address = new ServerAddress(); + ClusterDescription description = new ClusterDescription(SINGLE, STANDALONE, Collections.singletonList( + ServerDescription.builder().address(address).ok(true).state(com.mongodb.connection.ServerConnectionState.CONNECTED).build())); + ReadPreferenceServerSelector selector = new ReadPreferenceServerSelector(primary()); + + try (ScopeRecordingInterceptor interceptor = new ScopeRecordingInterceptor(applicationName, span)) { + BaseCluster.logServerSelectionStarted(operationContext, clusterId, selector, description); + BaseCluster.logServerSelectionWaiting(operationContext, clusterId, + operationContext.getTimeoutContext().computeServerSelectionTimeout(), selector, description); + BaseCluster.logServerSelectionFailed(operationContext, clusterId, new MongoTimeoutException("test"), selector, description); + BaseCluster.logServerSelectionSucceeded(operationContext, clusterId, address, selector, description); + + assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Server selection started")); + assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Waiting for suitable server to become available")); + assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Server selection failed")); + assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Server selection succeeded")); + assertEquals(span.openCount.get(), span.closeCount.get(), "scopes must be balanced"); + } + } + + static final class ScopeCountingSpan implements Span { + private final AtomicInteger openCount = new AtomicInteger(); + private final AtomicInteger closeCount = new AtomicInteger(); + + boolean isScopeOpen() { + return openCount.get() > closeCount.get(); + } + + @Override + public void openScope() { + openCount.incrementAndGet(); + } + + @Override + public void closeScope() { + closeCount.incrementAndGet(); + } + + @Override + public void setQueryText(final BsonDocument commandDocument) { + } + + @Override + public void event(final String event) { + } + + @Override + public void error(final Throwable throwable) { + } + + @Override + public void end() { + } + + @Override + public TraceContext context() { + return TraceContext.EMPTY; + } + + @Override + @Nullable + public MongodbObservationContext getMongodbObservationContext() { + return null; + } + + @Override + @Nullable + public MongoNamespace getNamespace() { + return null; + } + } +} From ab63bfbf5d68d2a16ee9707ac5649397b8f1fb5c Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 12 Nov 2026 16:35:35 +0000 Subject: [PATCH 06/36] JAVA-5734 Fix checkstyle violations in SpanScopesTest --- .../micrometer/SpanScopesTest.java | 64 +++++++++++++++---- 1 file changed, 53 insertions(+), 11 deletions(-) diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanScopesTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanScopesTest.java index 2f8da85f3f..72abff1836 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanScopesTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanScopesTest.java @@ -49,12 +49,21 @@ void opensScopeBeforeActionAndClosesAfter() { void closesScopeWhenActionThrows() { List calls = new ArrayList<>(); RuntimeException failure = new RuntimeException("appender failed"); - RuntimeException thrown = assertThrows(RuntimeException.class, - () -> SpanScopes.runInScope(new RecordingSpan(calls), () -> { throw failure; })); + RuntimeException thrown = assertThrows(RuntimeException.class, () -> SpanScopes.runInScope(new RecordingSpan(calls), () -> { + throw failure; + })); assertEquals(failure, thrown); assertEquals(asList("open", "close"), calls); } + @Test + void nestsScopes() { + List calls = new ArrayList<>(); + RecordingSpan span = new RecordingSpan(calls); + SpanScopes.runInScope(span, () -> SpanScopes.runInScope(span, () -> calls.add("action"))); + assertEquals(asList("open", "open", "action", "close", "close"), calls); + } + static final class RecordingSpan implements Span { private final List calls; @@ -62,14 +71,47 @@ static final class RecordingSpan implements Span { this.calls = calls; } - @Override public void openScope() { calls.add("open"); } - @Override public void closeScope() { calls.add("close"); } - @Override public void setQueryText(final BsonDocument commandDocument) { } - @Override public void event(final String event) { } - @Override public void error(final Throwable throwable) { } - @Override public void end() { } - @Override public TraceContext context() { return TraceContext.EMPTY; } - @Override @Nullable public MongodbObservationContext getMongodbObservationContext() { return null; } - @Override @Nullable public MongoNamespace getNamespace() { return null; } + @Override + public void openScope() { + calls.add("open"); + } + + @Override + public void closeScope() { + calls.add("close"); + } + + @Override + public void setQueryText(final BsonDocument commandDocument) { + } + + @Override + public void event(final String event) { + } + + @Override + public void error(final Throwable throwable) { + } + + @Override + public void end() { + } + + @Override + public TraceContext context() { + return TraceContext.EMPTY; + } + + @Override + @Nullable + public MongodbObservationContext getMongodbObservationContext() { + return null; + } + + @Override + @Nullable + public MongoNamespace getNamespace() { + return null; + } } } From cab737fe45a7c359a9f9f6ed04f47a6c94899e4c Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 12 Nov 2026 16:38:48 +0000 Subject: [PATCH 07/36] JAVA-5734 Emit connection checkout log messages inside the operation span scope --- .../connection/DefaultConnectionPool.java | 24 ++- .../DefaultConnectionPoolLogScopeTest.java | 168 ++++++++++++++++++ 2 files changed, 184 insertions(+), 8 deletions(-) create mode 100644 driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java diff --git a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java index a0a8bbe6e2..b08b6ce70c 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java +++ b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java @@ -52,6 +52,8 @@ import com.mongodb.internal.inject.OptionalProvider; import com.mongodb.internal.logging.LogMessage; import com.mongodb.internal.logging.StructuredLogger; +import com.mongodb.internal.observability.micrometer.Span; +import com.mongodb.internal.observability.micrometer.SpanScopes; import com.mongodb.internal.thread.DaemonThreadFactory; import com.mongodb.internal.time.StartTime; import com.mongodb.internal.time.Timeout; @@ -273,11 +275,12 @@ private Throwable checkOutFailed(final Throwable t, final OperationContext opera ClusterId clusterId = serverId.getClusterId(); if (requiresLogging(clusterId)) { String message = "Checkout failed for connection to {}:{}. Reason: {}.[ Error: {}.] Duration: {} ms"; - List entries = createBasicEntries(); + final List entries = createBasicEntries(); entries.add(new LogMessage.Entry(REASON_DESCRIPTION, EventReasonMessageResolver.getMessage(reason))); entries.add(new LogMessage.Entry(ERROR_DESCRIPTION, reason == Reason.CONNECTION_ERROR ? result.toString() : null)); entries.add(new LogMessage.Entry(DURATION_MS, checkoutDuration.toMillis())); - logMessage("Connection checkout failed", clusterId, message, entries); + SpanScopes.runInScope(operationContext.getTracingSpan(), + () -> logMessage("Connection checkout failed", clusterId, message, entries)); } connectionPoolListener.connectionCheckOutFailed( new ConnectionCheckOutFailedEvent(serverId, operationContext.getId(), reason, checkoutDuration.toNanos())); @@ -565,11 +568,12 @@ private void connectionCheckedOut( ConnectionId connectionId = getId(connection); ClusterId clusterId = serverId.getClusterId(); if (requiresLogging(clusterId)) { - List entries = createBasicEntries(); + final List entries = createBasicEntries(); entries.add(new LogMessage.Entry(DRIVER_CONNECTION_ID, connectionId.getLocalValue())); entries.add(new LogMessage.Entry(DURATION_MS, checkoutDuration.toMillis())); - logMessage("Connection checked out", clusterId, - "Connection checked out: address={}:{}, driver-generated ID={}, duration={} ms", entries); + SpanScopes.runInScope(operationContext.getTracingSpan(), + () -> logMessage("Connection checked out", clusterId, + "Connection checked out: address={}:{}, driver-generated ID={}, duration={} ms", entries)); } connectionPoolListener.connectionCheckedOut( @@ -585,7 +589,8 @@ private void connectionCheckedOut( */ private StartTime connectionCheckoutStarted(final OperationContext operationContext) { StartTime checkoutStart = StartTime.now(); - logEventMessage("Connection checkout started", "Checkout started for connection to {}:{}"); + SpanScopes.runInScope(operationContext.getTracingSpan(), + () -> logEventMessage("Connection checkout started", "Checkout started for connection to {}:{}")); connectionPoolListener.connectionCheckOutStarted(new ConnectionCheckOutStartedEvent(serverId, operationContext.getId())); return checkoutStart; @@ -615,6 +620,8 @@ private class PooledConnection implements InternalConnection { private final AtomicBoolean isClosed = new AtomicBoolean(); private Connection.PinningMode pinningMode; private long operationId; + @Nullable + private volatile Span operationSpan; PooledConnection(final UsageTrackingInternalConnection wrapped) { this.wrapped = notNull("wrapped", wrapped); @@ -630,6 +637,7 @@ public int getGeneration() { */ public void checkedOutForOperation(final OperationContext operationContext) { this.operationId = operationContext.getId(); + this.operationSpan = operationContext.getTracingSpan(); } @Override @@ -677,9 +685,9 @@ public void close() { private void connectionCheckedIn() { ConnectionId connectionId = getId(wrapped); - logEventMessage("Connection checked in", + SpanScopes.runInScope(operationSpan, () -> logEventMessage("Connection checked in", "Connection checked in: address={}:{}, driver-generated ID={}", - connectionId.getLocalValue()); + connectionId.getLocalValue())); connectionPoolListener.connectionCheckedIn(new ConnectionCheckedInEvent(connectionId, operationId)); } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java new file mode 100644 index 0000000000..e4858c54f5 --- /dev/null +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java @@ -0,0 +1,168 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.connection; + +import com.mongodb.MongoNamespace; +import com.mongodb.ServerAddress; +import com.mongodb.connection.ClusterId; +import com.mongodb.connection.ConnectionPoolSettings; +import com.mongodb.connection.ServerId; +import com.mongodb.internal.inject.SameObjectProvider; +import com.mongodb.internal.logging.LogMessage; +import com.mongodb.internal.observability.micrometer.Span; +import com.mongodb.internal.observability.micrometer.TraceContext; +import com.mongodb.lang.Nullable; +import com.mongodb.logging.TestLoggingInterceptor; +import com.mongodb.observability.micrometer.MongodbObservationContext; +import org.bson.BsonDocument; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; + +import static com.mongodb.ClusterFixture.OPERATION_CONTEXT_FACTORY; +import static com.mongodb.ClusterFixture.createOperationContext; +import static com.mongodb.internal.logging.LogMessage.Component.CONNECTION; +import static com.mongodb.internal.logging.LogMessage.Level.DEBUG; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; + +final class DefaultConnectionPoolLogScopeTest { + + @Test + void checkoutMessagesAreEmittedInsideTheOperationSpanScope() { + String applicationName = "DefaultConnectionPoolLogScopeTest"; + ServerId serverId = new ServerId(new ClusterId(applicationName), new ServerAddress()); + ScopeCountingSpan span = new ScopeCountingSpan(); + OperationContext operationContext = createOperationContext(); + operationContext.setTracingSpan(span); + DefaultConnectionPool pool = new DefaultConnectionPool(serverId, new TestInternalConnectionFactory(), + ConnectionPoolSettings.builder().maxSize(1).build(), + SameObjectProvider.initialized(mock(SdamServerDescriptionManager.class)), OPERATION_CONTEXT_FACTORY); + pool.ready(); + + try (ScopeRecordingInterceptor interceptor = new ScopeRecordingInterceptor(applicationName, span)) { + InternalConnection connection = pool.get(operationContext); + connection.close(); // check in + + assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Connection checkout started")); + assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Connection checked out")); + assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Connection checked in")); + assertEquals(span.openCount.get(), span.closeCount.get(), "scopes must be balanced"); + } finally { + pool.close(); + } + } + + @Test + void checkedInMessageUsesTheSpanOfTheMostRecentCheckout() { + String applicationName = "DefaultConnectionPoolLogScopeTest2"; + ServerId serverId = new ServerId(new ClusterId(applicationName), new ServerAddress()); + ScopeCountingSpan firstSpan = new ScopeCountingSpan(); + ScopeCountingSpan secondSpan = new ScopeCountingSpan(); + OperationContext first = createOperationContext(); + first.setTracingSpan(firstSpan); + OperationContext second = createOperationContext(); + second.setTracingSpan(secondSpan); + DefaultConnectionPool pool = new DefaultConnectionPool(serverId, new TestInternalConnectionFactory(), + ConnectionPoolSettings.builder().maxSize(1).build(), + SameObjectProvider.initialized(mock(SdamServerDescriptionManager.class)), OPERATION_CONTEXT_FACTORY); + pool.ready(); + + try (ScopeRecordingInterceptor interceptor = new ScopeRecordingInterceptor(applicationName, secondSpan)) { + pool.get(first).close(); + interceptor.scopeOpenAtMessage.clear(); + pool.get(second).close(); + + assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Connection checked in"), + "checked in must use the span of the second checkout, not the first"); + assertEquals(0, firstSpan.openCount.get() - firstSpan.closeCount.get()); + } finally { + pool.close(); + } + } + + private static final class ScopeRecordingInterceptor extends TestLoggingInterceptor { + private final ScopeCountingSpan span; + private final Map scopeOpenAtMessage = new ConcurrentHashMap<>(); + + ScopeRecordingInterceptor(final String applicationName, final ScopeCountingSpan span) { + super(applicationName, new LoggingFilter(Collections.singletonMap(CONNECTION, DEBUG))); + this.span = span; + } + + @Override + public synchronized void intercept(final LogMessage message) { + super.intercept(message); + scopeOpenAtMessage.put(message.getMessageId(), span.isScopeOpen()); + } + } + + static final class ScopeCountingSpan implements Span { + private final AtomicInteger openCount = new AtomicInteger(); + private final AtomicInteger closeCount = new AtomicInteger(); + + boolean isScopeOpen() { + return openCount.get() > closeCount.get(); + } + + @Override + public void openScope() { + openCount.incrementAndGet(); + } + + @Override + public void closeScope() { + closeCount.incrementAndGet(); + } + + @Override + public void setQueryText(final BsonDocument commandDocument) { + } + + @Override + public void event(final String event) { + } + + @Override + public void error(final Throwable throwable) { + } + + @Override + public void end() { + } + + @Override + public TraceContext context() { + return TraceContext.EMPTY; + } + + @Override + @Nullable + public MongodbObservationContext getMongodbObservationContext() { + return null; + } + + @Override + @Nullable + public MongoNamespace getNamespace() { + return null; + } + } +} From fa2180dac6c77bbedd94efc6df3275dbe2efa66b Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 12 Nov 2026 16:42:05 +0000 Subject: [PATCH 08/36] JAVA-5734 Only open the operation span scope when connection logging is required --- .../internal/connection/DefaultConnectionPool.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java index b08b6ce70c..6340952c4c 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java +++ b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java @@ -589,8 +589,10 @@ private void connectionCheckedOut( */ private StartTime connectionCheckoutStarted(final OperationContext operationContext) { StartTime checkoutStart = StartTime.now(); - SpanScopes.runInScope(operationContext.getTracingSpan(), - () -> logEventMessage("Connection checkout started", "Checkout started for connection to {}:{}")); + if (requiresLogging(serverId.getClusterId())) { + SpanScopes.runInScope(operationContext.getTracingSpan(), + () -> logEventMessage("Connection checkout started", "Checkout started for connection to {}:{}")); + } connectionPoolListener.connectionCheckOutStarted(new ConnectionCheckOutStartedEvent(serverId, operationContext.getId())); return checkoutStart; @@ -685,9 +687,11 @@ public void close() { private void connectionCheckedIn() { ConnectionId connectionId = getId(wrapped); - SpanScopes.runInScope(operationSpan, () -> logEventMessage("Connection checked in", - "Connection checked in: address={}:{}, driver-generated ID={}", - connectionId.getLocalValue())); + if (requiresLogging(serverId.getClusterId())) { + SpanScopes.runInScope(operationSpan, () -> logEventMessage("Connection checked in", + "Connection checked in: address={}:{}, driver-generated ID={}", + connectionId.getLocalValue())); + } connectionPoolListener.connectionCheckedIn(new ConnectionCheckedInEvent(connectionId, operationId)); } From 7d7e1fb68cb4be649dc224d1eb1b4b7207b4e968 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 12 Nov 2026 16:50:07 +0000 Subject: [PATCH 09/36] JAVA-5734 Add OpenTelemetry prose tests 10-13 and 15 for log/trace correlation --- .../client/AbstractMicrometerProseTest.java | 240 ++++++++++++++++++ 1 file changed, 240 insertions(+) diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java index 03842d5378..7ffb7e8503 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java @@ -17,7 +17,13 @@ package com.mongodb.client; import com.mongodb.MongoClientSettings; +import com.mongodb.MongoTimeoutException; +import com.mongodb.ServerAddress; import com.mongodb.internal.EnvironmentProvider; +import com.mongodb.internal.logging.LogMessage; +import com.mongodb.internal.logging.LoggingInterceptor; +import com.mongodb.internal.logging.StructuredLogger; +import com.mongodb.lang.Nullable; import com.mongodb.observability.micrometer.MongodbObservationContext; import com.mongodb.observability.micrometer.MongodbObservation; import com.mongodb.observability.ObservabilitySettings; @@ -30,6 +36,7 @@ import io.micrometer.observation.ObservationRegistry; import io.micrometer.tracing.exporter.FinishedSpan; import io.micrometer.tracing.test.reporter.inmemory.InMemoryOtelSetup; +import org.bson.BsonDocument; import org.bson.Document; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; @@ -39,6 +46,7 @@ import org.junit.jupiter.api.Test; import java.util.ArrayList; +import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -51,13 +59,22 @@ import java.util.stream.Collectors; import static com.mongodb.ClusterFixture.getDefaultDatabaseName; +import static com.mongodb.ClusterFixture.getPrimary; +import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet; +import static com.mongodb.ClusterFixture.isSharded; +import static com.mongodb.ClusterFixture.serverVersionAtLeast; import static com.mongodb.client.Fixture.getMongoClientSettingsBuilder; import static com.mongodb.observability.micrometer.MongodbObservation.HighCardinalityKeyNames.QUERY_TEXT; import static com.mongodb.internal.observability.micrometer.TracingManager.ENV_OBSERVABILITY_ENABLED; import static com.mongodb.internal.observability.micrometer.TracingManager.ENV_OBSERVABILITY_QUERY_TEXT_MAX_LENGTH; +import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * Implementation of the prose tests @@ -422,4 +439,227 @@ public KeyValues getLowCardinalityKeyValues(final MongodbObservationContext cont "Custom convention should carry over 'db.system.name' on operation span."); } } + + @DisplayName("Test 10: Command log messages carry their own command span") + @Test + void testCommandLogMessagesCarryTheirOwnCommandSpan() { + // the retry on error code 91 requires retryable reads, which need a replica set or a sharded cluster + assumeTrue(serverVersionAtLeast(4, 4)); + assumeTrue(isDiscoverableReplicaSet() || isSharded()); + String appName = "otel-log-test10"; + BsonDocument failPoint = BsonDocument.parse("{ configureFailPoint: 'failCommand', mode: { times: 1 }," + + " data: { failCommands: ['find'], errorCode: 91, appName: '" + appName + "' } }"); + // error code 91 marks the server Unknown; a short heartbeat lets the retry rediscover it quickly + MongoClientSettings settings = MongoClientSettings.builder(tracedSettings(appName)) + .applyToServerSettings(b -> b.heartbeatFrequency(500, TimeUnit.MILLISECONDS)) + .build(); + try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); + MongoClient client = createMongoClient(settings); + FailPoint ignored = FailPoint.enable(failPoint, getPrimary())) { + client.getDatabase(getDefaultDatabaseName()).getCollection("test").find().first(); + + List spans = inMemoryOtel.getFinishedSpans(); + FinishedSpan firstAttempt = spanNamed(spans, "find", 0); + FinishedSpan secondAttempt = spanNamed(spans, "find", 1); + FinishedSpan operation = spanNamed(spans, "find " + getDefaultDatabaseName() + ".test", 0); + + List started = logs.messages("Command started").stream() + .filter(l -> operation.getTraceId().equals(l.traceId)).collect(Collectors.toList()); + assertEquals(2, started.size(), "one started message per attempt"); + assertEquals(firstAttempt.getSpanId(), started.get(0).spanId); + assertEquals(secondAttempt.getSpanId(), started.get(1).spanId); + + List failed = logs.messages("Command failed"); + assertEquals(1, failed.size()); + assertEquals(firstAttempt.getSpanId(), failed.get(0).spanId); + + List succeeded = logs.messages("Command succeeded").stream() + .filter(l -> secondAttempt.getTraceId().equals(l.traceId)).collect(Collectors.toList()); + assertEquals(1, succeeded.size()); + assertEquals(secondAttempt.getSpanId(), succeeded.get(0).spanId); + + for (ObservedLog l : logs.component(LogMessage.Component.COMMAND)) { + assertNotEquals(operation.getSpanId(), l.spanId, "command messages must not carry the operation span"); + } + } + } + + @DisplayName("Test 11: Operation-path log messages carry the operation span") + @Test + void testOperationPathLogMessagesCarryTheOperationSpan() { + String operationName = "insert " + getDefaultDatabaseName() + ".test"; + String appName = "otel-log-test11"; + String succeedingTraceId; + try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); + MongoClient client = createMongoClient(tracedSettings(appName))) { + client.getDatabase(getDefaultDatabaseName()).getCollection("test").insertOne(new Document("x", 1)); + + FinishedSpan operation = spanNamed(inMemoryOtel.getFinishedSpans(), operationName, 0); + succeedingTraceId = operation.getTraceId(); + for (String messageId : asList("Server selection started", "Server selection succeeded", + "Connection checkout started", "Connection checked out", "Connection checked in")) { + List observed = logs.messages(messageId).stream() + .filter(l -> operation.getTraceId().equals(l.traceId)).collect(Collectors.toList()); + assertFalse(observed.isEmpty(), messageId + " must be emitted inside the operation's trace"); + for (ObservedLog l : observed) { + assertEquals(operation.getSpanId(), l.spanId, messageId + " must carry the operation span"); + } + } + } + + String failingAppName = "otel-log-test11-failing"; + MongoClientSettings failing = MongoClientSettings.builder(tracedSettings(failingAppName)) + .applyToClusterSettings(b -> b.hosts(singletonList(new ServerAddress("localhost", 1))) + .serverSelectionTimeout(500, TimeUnit.MILLISECONDS)) + .build(); + try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(failingAppName, inMemoryOtel.getTracer()); + MongoClient client = createMongoClient(failing)) { + assertThrows(MongoTimeoutException.class, + () -> client.getDatabase(getDefaultDatabaseName()).getCollection("test").insertOne(new Document("x", 1))); + + // the failing operation is the only one outside the trace of the succeeding operation above + List failingOperations = inMemoryOtel.getFinishedSpans().stream() + .filter(s -> s.getName().equals(operationName) && !s.getTraceId().equals(succeedingTraceId)) + .collect(Collectors.toList()); + assertEquals(1, failingOperations.size(), "expected one failing operation span but got " + failingOperations); + FinishedSpan operation = failingOperations.get(0); + for (String messageId : asList("Waiting for suitable server to become available", "Server selection failed")) { + List observed = logs.messages(messageId); + assertFalse(observed.isEmpty(), messageId + " must be emitted"); + for (ObservedLog l : observed) { + assertEquals(operation.getTraceId(), l.traceId, messageId + " must carry the operation's trace"); + assertEquals(operation.getSpanId(), l.spanId, messageId + " must carry the operation span"); + } + } + } + } + + @DisplayName("Test 12: Command log messages inside a transaction carry the command span and the transaction's trace") + @Test + void testLogMessagesInsideTransaction() { + assumeTrue(isDiscoverableReplicaSet() || isSharded()); + String appName = "otel-log-test12"; + try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); + MongoClient client = createMongoClient(tracedSettings(appName)); + ClientSession session = client.startSession()) { + MongoCollection collection = client.getDatabase(getDefaultDatabaseName()).getCollection("test"); + // explicit start/commit rather than withTransaction, which the reactive sync adapter does not support + session.startTransaction(); + collection.insertOne(session, new Document("x", 1)); + session.commitTransaction(); + + List spans = inMemoryOtel.getFinishedSpans(); + FinishedSpan transaction = spanNamed(spans, "transaction", 0); + FinishedSpan insertCommand = spanNamed(spans, "insert", 0); + List started = logs.messages("Command started").stream() + .filter(l -> transaction.getTraceId().equals(l.traceId)).collect(Collectors.toList()); + assertFalse(started.isEmpty(), "command started messages must carry the transaction's trace"); + ObservedLog insertStarted = started.stream().filter(l -> insertCommand.getSpanId().equals(l.spanId)).findFirst() + .orElseThrow(() -> new AssertionError("insert started message must carry the insert command span")); + assertEquals(transaction.getTraceId(), insertStarted.traceId); + } + } + + // Test 14 (trace context fields in structured log messages) does not apply to Java: the driver logs through SLF4J and + // adds no trace fields of its own. + @DisplayName("Test 13: Background log messages are not attributed to an operation") + @Test + void testBackgroundLogMessagesAreNotAttributedToAnOperation() throws InterruptedException { + String appName = "otel-log-test13"; + MongoClientSettings settings = MongoClientSettings.builder(tracedSettings(appName)) + .applyToServerSettings(b -> b.heartbeatFrequency(100, TimeUnit.MILLISECONDS)) + .build(); + try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); + MongoClient client = createMongoClient(settings)) { + client.getDatabase(getDefaultDatabaseName()).getCollection("test").insertOne(new Document("x", 1)); + int topologyMessagesBefore = logs.component(LogMessage.Component.TOPOLOGY).size(); + long deadline = System.currentTimeMillis() + 5_000; + while (logs.component(LogMessage.Component.TOPOLOGY).size() == topologyMessagesBefore + && System.currentTimeMillis() < deadline) { + Thread.sleep(50); + } + Set operationTraceIds = inMemoryOtel.getFinishedSpans().stream() + .map(FinishedSpan::getTraceId).collect(Collectors.toSet()); + assertFalse(operationTraceIds.isEmpty(), "the operation must have produced spans"); + List background = logs.component(LogMessage.Component.TOPOLOGY); + assertTrue(background.size() > topologyMessagesBefore, "a heartbeat message must have been logged after the operation"); + for (ObservedLog l : background) { + assertFalse(l.traceId != null && operationTraceIds.contains(l.traceId), + l.messageId + " must not carry the trace of a driver operation"); + } + } + } + + private MongoClientSettings tracedSettings(final String applicationName) { + // tracing is enabled by default; clear any override left by another test + environmentOverride.set(ENV_OBSERVABILITY_ENABLED, null); + return getMongoClientSettingsBuilder() + .applicationName(applicationName) + .observabilitySettings(ObservabilitySettings.micrometerBuilder() + .observationRegistry(observationRegistry) + .build()) + .build(); + } + + private static FinishedSpan spanNamed(final List spans, final String name, final int index) { + List matching = spans.stream().filter(s -> s.getName().equals(name)).collect(Collectors.toList()); + assertTrue(matching.size() > index, "expected at least " + (index + 1) + " spans named " + name + " but got " + matching); + return matching.get(index); + } + + /** Trace id and span id that were current on the thread when a log message was emitted. */ + private static final class ObservedLog { + private final String messageId; + private final LogMessage.Component component; + @Nullable + private final String traceId; + @Nullable + private final String spanId; + + ObservedLog(final LogMessage message, @Nullable final io.micrometer.tracing.Span current) { + this.messageId = message.getMessageId(); + this.component = message.getComponent(); + this.traceId = current == null ? null : current.context().traceId(); + this.spanId = current == null ? null : current.context().spanId(); + } + } + + /** + * Records, for each log message of the client with the given application name, the span current on the emitting thread. + * {@link StructuredLogger#log(LogMessage)} calls the interceptor on the emitting thread, so this observes exactly what an + * MDC bridge would. + */ + private static final class SpanRecordingInterceptor implements LoggingInterceptor, AutoCloseable { + private final String applicationName; + private final io.micrometer.tracing.Tracer tracer; + private final List logs = Collections.synchronizedList(new ArrayList<>()); + + SpanRecordingInterceptor(final String applicationName, final io.micrometer.tracing.Tracer tracer) { + this.applicationName = applicationName; + this.tracer = tracer; + StructuredLogger.addInterceptor(applicationName, this); + } + + @Override + public void intercept(final LogMessage message) { + logs.add(new ObservedLog(message, tracer.currentSpan())); + } + + List messages(final String messageId) { + synchronized (logs) { + return logs.stream().filter(l -> l.messageId.equals(messageId)).collect(Collectors.toList()); + } + } + + List component(final LogMessage.Component component) { + synchronized (logs) { + return logs.stream().filter(l -> l.component == component).collect(Collectors.toList()); + } + } + + @Override + public void close() { + StructuredLogger.removeInterceptor(applicationName); + } + } } From 20bcaf22df789d3478d4eb1e2877761b4c0e7e67 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 12 Nov 2026 16:54:42 +0000 Subject: [PATCH 10/36] JAVA-5734 Strengthen trace assertions in prose tests 10 and 12 --- .../client/AbstractMicrometerProseTest.java | 31 +++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java index 7ffb7e8503..7108ca497a 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java @@ -472,11 +472,13 @@ void testCommandLogMessagesCarryTheirOwnCommandSpan() { List failed = logs.messages("Command failed"); assertEquals(1, failed.size()); assertEquals(firstAttempt.getSpanId(), failed.get(0).spanId); + assertEquals(firstAttempt.getTraceId(), failed.get(0).traceId); List succeeded = logs.messages("Command succeeded").stream() .filter(l -> secondAttempt.getTraceId().equals(l.traceId)).collect(Collectors.toList()); assertEquals(1, succeeded.size()); assertEquals(secondAttempt.getSpanId(), succeeded.get(0).spanId); + assertEquals(secondAttempt.getTraceId(), succeeded.get(0).traceId); for (ObservedLog l : logs.component(LogMessage.Component.COMMAND)) { assertNotEquals(operation.getSpanId(), l.spanId, "command messages must not carry the operation span"); @@ -551,12 +553,29 @@ void testLogMessagesInsideTransaction() { List spans = inMemoryOtel.getFinishedSpans(); FinishedSpan transaction = spanNamed(spans, "transaction", 0); FinishedSpan insertCommand = spanNamed(spans, "insert", 0); - List started = logs.messages("Command started").stream() - .filter(l -> transaction.getTraceId().equals(l.traceId)).collect(Collectors.toList()); - assertFalse(started.isEmpty(), "command started messages must carry the transaction's trace"); - ObservedLog insertStarted = started.stream().filter(l -> insertCommand.getSpanId().equals(l.spanId)).findFirst() - .orElseThrow(() -> new AssertionError("insert started message must carry the insert command span")); - assertEquals(transaction.getTraceId(), insertStarted.traceId); + FinishedSpan commitCommand = spanNamed(spans, "commitTransaction", 0); + for (FinishedSpan command : asList(insertCommand, commitCommand)) { + assertEquals(transaction.getTraceId(), command.getTraceId(), command.getName() + " must be in the transaction's trace"); + for (String messageId : asList("Command started", "Command succeeded")) { + List observed = logs.messages(messageId).stream() + .filter(l -> command.getSpanId().equals(l.spanId)).collect(Collectors.toList()); + assertEquals(1, observed.size(), messageId + " must carry the " + command.getName() + " command span"); + assertEquals(transaction.getTraceId(), observed.get(0).traceId, + messageId + " for " + command.getName() + " must carry the transaction's trace"); + } + } + + // command spans are named after the command alone; operation spans add the namespace + Set commandSpanIds = spans.stream() + .filter(s -> transaction.getTraceId().equals(s.getTraceId())) + .filter(s -> !s.getName().equals("transaction") && !s.getName().contains(" ")) + .map(FinishedSpan::getSpanId).collect(Collectors.toSet()); + for (ObservedLog l : logs.component(LogMessage.Component.COMMAND)) { + if (transaction.getTraceId().equals(l.traceId)) { + assertNotEquals(transaction.getSpanId(), l.spanId, l.messageId + " must not carry the transaction span"); + assertTrue(commandSpanIds.contains(l.spanId), l.messageId + " must carry a command span of the transaction"); + } + } } } From c0cd96c51609ee574ecedf65951a48b47b566211 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 12 Nov 2026 17:08:10 +0000 Subject: [PATCH 11/36] JAVA-5734 Address final review: clear per-thread scope state and fix comment Remove the per-thread scope entry once its deque is empty and never create it on an unmatched close, so balanced use leaves no ThreadLocal behind. Add tests for the thread-local lifecycle and for restoring the tracing context across nested scopes, and correct the InternalStreamConnection comment about command event suppression. --- .../connection/InternalStreamConnection.java | 3 +- .../micrometer/MicrometerTracer.java | 23 ++++++++-- .../micrometer/MicrometerSpanScopeTest.java | 43 +++++++++++++++++++ 3 files changed, 64 insertions(+), 5 deletions(-) diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java index 3dcbb04393..8cf98d8869 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java @@ -454,8 +454,7 @@ private T sendAndReceiveInternal(final CommandMessage message, final Decoder Span tracingSpan = null; // Single owner of the span and event sender until the message is handed off to the receive phase: // any failure from span creation through sendCommandMessage ends the span exactly once and emits at - // most one failed event (LoggingCommandEventSender suppresses terminal events until the started event - // has completed, and Span.closeScope() is a no-op if no scope was opened). + // most one failed event; closing a span scope that was never opened is a no-op. try (ByteBufferBsonOutput bsonOutput = new ByteBufferBsonOutput(this)) { tracingSpan = operationContext .getTracingManager() diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java index f7b3283e46..676bf462cb 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java @@ -244,7 +244,7 @@ static class MicrometerSpan implements Span { @Nullable private final MongoNamespace namespace; private final int queryTextLength; - private final ThreadLocal> scopes = ThreadLocal.withInitial(ArrayDeque::new); + private final ThreadLocal> scopes = new ThreadLocal<>(); /** * Constructs a new {@link MicrometerSpan} instance with an associated Observation and MongoDB namespace. @@ -261,15 +261,32 @@ static class MicrometerSpan implements Span { @Override public void openScope() { - scopes.get().push(observation.openScope()); + Deque deque = scopes.get(); + if (deque == null) { + deque = new ArrayDeque<>(); + scopes.set(deque); + } + deque.push(observation.openScope()); } @Override public void closeScope() { - Observation.Scope scope = scopes.get().poll(); + Deque deque = scopes.get(); + if (deque == null) { + return; + } + Observation.Scope scope = deque.poll(); if (scope != null) { scope.close(); } + if (deque.isEmpty()) { + scopes.remove(); + } + } + + // visible for testing + boolean isThreadLocalEmpty() { + return scopes.get() == null; } @Override diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java index f94092b369..a80b3e01d0 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java @@ -19,14 +19,19 @@ import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationRegistry; import io.micrometer.observation.tck.TestObservationRegistry; +import io.micrometer.tracing.handler.DefaultTracingObservationHandler; +import io.micrometer.tracing.handler.TracingObservationHandler; +import io.micrometer.tracing.test.simple.SimpleTracer; import org.junit.jupiter.api.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; class MicrometerSpanScopeTest { @@ -120,6 +125,44 @@ void aThreadsCloseDoesNotCloseAnotherThreadsScope() throws Exception { observation.stop(); } + @Test + void balancedOpenAndCloseLeaveNoThreadLocalEntry() { + ObservationRegistry registry = TestObservationRegistry.create(); + Observation observation = Observation.start("op", registry); + MicrometerTracer.MicrometerSpan span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); + + assertTrue(span.isThreadLocalEmpty(), "no thread-local entry may exist before the first open"); + span.closeScope(); + assertTrue(span.isThreadLocalEmpty(), "an unmatched close must not create a thread-local entry"); + span.openScope(); + assertFalse(span.isThreadLocalEmpty(), "an open scope must be tracked"); + span.closeScope(); + assertTrue(span.isThreadLocalEmpty(), "a balanced open/close must clear the thread-local"); + observation.stop(); + } + + @Test + void nestedScopesRestoreTheOuterTracingContext() { + ObservationRegistry registry = ObservationRegistry.create(); + SimpleTracer tracer = new SimpleTracer(); + registry.observationConfig().observationHandler(new DefaultTracingObservationHandler(tracer)); + Observation observation = Observation.start("op", registry); + TracingObservationHandler.TracingContext tracingContext = + observation.getContextView().get(TracingObservationHandler.TracingContext.class); + io.micrometer.tracing.Span observationSpan = tracingContext.getSpan(); + Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); + + span.openScope(); + span.openScope(); + span.closeScope(); + assertSame(observationSpan, tracer.currentSpan(), "the observation's span must still be current after the inner close"); + assertSame(observation, registry.getCurrentObservation(), "the observation itself must still be current"); + span.closeScope(); + assertNull(tracer.currentSpan(), "no span may remain current after balanced closes"); + assertNull(registry.getCurrentObservation(), "no observation may remain current after balanced closes"); + observation.stop(); + } + @Test void extraCloseIsNoOp() { ObservationRegistry registry = TestObservationRegistry.create(); From 0bb84f84753976d4d5eee2c806c1eb502f0d8d64 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 12 Nov 2026 17:08:10 +0000 Subject: [PATCH 12/36] JAVA-5734 Assert no span remains current after traced operations Check the OTel current span and the current observation after prose tests 10, 11 and 12, and skip the failing half of test 11 on SRV and load-balanced fixtures where a fixed localhost host list cannot time out. --- .../client/AbstractMicrometerProseTest.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java index 7108ca497a..22669ef49a 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java @@ -58,9 +58,11 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import static com.mongodb.ClusterFixture.getConnectionString; import static com.mongodb.ClusterFixture.getDefaultDatabaseName; import static com.mongodb.ClusterFixture.getPrimary; import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet; +import static com.mongodb.ClusterFixture.isLoadBalanced; import static com.mongodb.ClusterFixture.isSharded; import static com.mongodb.ClusterFixture.serverVersionAtLeast; import static com.mongodb.client.Fixture.getMongoClientSettingsBuilder; @@ -72,8 +74,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.junit.jupiter.api.Assumptions.assumeTrue; /** @@ -457,6 +461,7 @@ void testCommandLogMessagesCarryTheirOwnCommandSpan() { MongoClient client = createMongoClient(settings); FailPoint ignored = FailPoint.enable(failPoint, getPrimary())) { client.getDatabase(getDefaultDatabaseName()).getCollection("test").find().first(); + assertNoSpanIsCurrent(); List spans = inMemoryOtel.getFinishedSpans(); FinishedSpan firstAttempt = spanNamed(spans, "find", 0); @@ -495,6 +500,7 @@ void testOperationPathLogMessagesCarryTheOperationSpan() { try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); MongoClient client = createMongoClient(tracedSettings(appName))) { client.getDatabase(getDefaultDatabaseName()).getCollection("test").insertOne(new Document("x", 1)); + assertNoSpanIsCurrent(); FinishedSpan operation = spanNamed(inMemoryOtel.getFinishedSpans(), operationName, 0); succeedingTraceId = operation.getTraceId(); @@ -509,6 +515,10 @@ void testOperationPathLogMessagesCarryTheOperationSpan() { } } + // a fixed localhost host list is incompatible with an SRV fixture, and a load-balanced fixture would not time out + assumeFalse(getConnectionString().isSrvProtocol()); + assumeFalse(isLoadBalanced()); + String failingAppName = "otel-log-test11-failing"; MongoClientSettings failing = MongoClientSettings.builder(tracedSettings(failingAppName)) .applyToClusterSettings(b -> b.hosts(singletonList(new ServerAddress("localhost", 1))) @@ -518,6 +528,7 @@ void testOperationPathLogMessagesCarryTheOperationSpan() { MongoClient client = createMongoClient(failing)) { assertThrows(MongoTimeoutException.class, () -> client.getDatabase(getDefaultDatabaseName()).getCollection("test").insertOne(new Document("x", 1))); + assertNoSpanIsCurrent(); // the failing operation is the only one outside the trace of the succeeding operation above List failingOperations = inMemoryOtel.getFinishedSpans().stream() @@ -549,6 +560,7 @@ void testLogMessagesInsideTransaction() { session.startTransaction(); collection.insertOne(session, new Document("x", 1)); session.commitTransaction(); + assertNoSpanIsCurrent(); List spans = inMemoryOtel.getFinishedSpans(); FinishedSpan transaction = spanNamed(spans, "transaction", 0); @@ -620,6 +632,11 @@ private MongoClientSettings tracedSettings(final String applicationName) { .build(); } + private void assertNoSpanIsCurrent() { + assertNull(inMemoryOtel.getTracer().currentSpan(), "no span may be current after the operation"); + assertNull(observationRegistry.getCurrentObservation(), "no observation may be current after the operation"); + } + private static FinishedSpan spanNamed(final List spans, final String name, final int index) { List matching = spans.stream().filter(s -> s.getName().equals(name)).collect(Collectors.toList()); assertTrue(matching.size() > index, "expected at least " + (index + 1) + " spans named " + name + " but got " + matching); From d68b0a70685efa7941c50a01740ab429054780a3 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Sun, 15 Nov 2026 17:49:06 +0000 Subject: [PATCH 13/36] JAVA-5734 Document and test the TransactionSpan cross-thread scope behaviour --- .../micrometer/TransactionSpan.java | 10 ++ .../micrometer/TransactionSpanScopeTest.java | 141 ++++++++++++++++++ 2 files changed, 151 insertions(+) create mode 100644 driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanScopeTest.java diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java index 03a6301b02..92da86fadd 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java @@ -20,6 +20,12 @@ /** * State class for transaction tracing. + *

+ * The scope opened by {@link #openScope()} is bound to the thread that opened it and must be closed on that same + * thread, via {@link #finalizeTransactionSpan}, {@link #handleTransactionSpanError} or {@link #spanFinalizing}. + * Committing or aborting the transaction on a different thread makes the close a no-op there and leaves the + * opening thread's current observation set to the transaction span after it has ended. A follow-up will revisit + * the transaction scope lifetime. * * @since 5.7 */ @@ -116,6 +122,10 @@ public TraceContext getContext() { /** * Opens a scope for the transaction span, making it the current observation on the thread. * Must only be called from the sync driver where open and close happen on the same thread. + *

+ * The scope is thread-bound: it must be closed on the same thread that opened it. Closing it from another + * thread is a no-op there and leaves this thread's current observation as the (ended) transaction span. + * A follow-up will revisit the transaction scope lifetime. */ public void openScope() { span.openScope(); diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanScopeTest.java new file mode 100644 index 0000000000..b22deb0dd9 --- /dev/null +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanScopeTest.java @@ -0,0 +1,141 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.observability.micrometer; + +import com.mongodb.observability.ObservabilitySettings; +import com.mongodb.observability.micrometer.MongodbObservation; +import io.micrometer.observation.Observation; +import io.micrometer.observation.ObservationRegistry; +import io.micrometer.observation.tck.TestObservationRegistry; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +/** + * Pins the thread-bound lifetime of the scope opened by {@link TransactionSpan#openScope()}. + *

+ * {@link MicrometerTracer.MicrometerSpan} tracks open scopes per thread, so committing or aborting a transaction + * on a thread other than the one that started it does not restore the opening thread's previous observation. This + * is pre-existing behaviour that a follow-up will revisit; these tests make it explicit instead of accidental. + */ +class TransactionSpanScopeTest { + + @Test + void openAndFinalizeOnTheSameThreadRestoreThePreviousObservation() { + TestObservationRegistry registry = TestObservationRegistry.create(); + TransactionSpan transactionSpan = new TransactionSpan(tracingManager(registry)); + + assertNull(registry.getCurrentObservation(), "no observation is current before the transaction starts"); + + transactionSpan.openScope(); + Observation current = registry.getCurrentObservation(); + assertNotNull(current, "the transaction span must be the current observation on the opening thread"); + assertEquals(MongodbObservation.MONGODB_TRANSACTION.getName(), current.getContext().getName(), + "the current observation must be the transaction observation"); + + transactionSpan.finalizeTransactionSpan("COMMITTED"); + assertNull(registry.getCurrentObservation(), "finalizing on the opening thread must close its scope"); + } + + @Test + void finalizeOnAnotherThreadIsANoOpThereAndLeavesTheOpenerScopeCurrent() throws Exception { + ObservationRegistry registry = realObservationRegistry(); + TransactionSpan transactionSpan = new TransactionSpan(tracingManager(registry)); + + transactionSpan.openScope(); // thread A (this thread) opens the scope + Observation transactionObservation = registry.getCurrentObservation(); + assertNotNull(transactionObservation); + assertEquals(MongodbObservation.MONGODB_TRANSACTION.getName(), + transactionObservation.getContext().getName()); + + ExecutorService threadB = Executors.newSingleThreadExecutor(); + try { + threadB.submit(() -> { + assertNull(registry.getCurrentObservation(), "thread B has no current observation before the call"); + transactionSpan.finalizeTransactionSpan("COMMITTED"); + // closeScope() is per-thread: thread B has no scope of its own to pop, so the close is a no-op there. + assertNull(registry.getCurrentObservation(), "finalizing on thread B must not make the span current there"); + }).get(); // surface thread B's failures on this thread + } finally { + threadB.shutdown(); + } + + assertSame(transactionObservation, registry.getCurrentObservation(), + "thread A's current observation is still the transaction span, even though it has ended"); + + // Test cleanup only, not a recommended pattern: this second call pops thread A's scope and stops the + // already-stopped observation again. + assertDoesNotThrow(() -> transactionSpan.spanFinalizing(true), "stopping a stopped observation must not throw"); + assertNull(registry.getCurrentObservation(), "cleanup must leave no scope open on the opening thread"); + } + + @Test + void handleTransactionSpanErrorOnAnotherThreadBehavesTheSame() throws Exception { + ObservationRegistry registry = realObservationRegistry(); + TransactionSpan transactionSpan = new TransactionSpan(tracingManager(registry)); + + transactionSpan.openScope(); // thread A (this thread) opens the scope + Observation transactionObservation = registry.getCurrentObservation(); + assertNotNull(transactionObservation); + assertEquals(MongodbObservation.MONGODB_TRANSACTION.getName(), + transactionObservation.getContext().getName()); + + ExecutorService threadB = Executors.newSingleThreadExecutor(); + try { + threadB.submit(() -> { + assertNull(registry.getCurrentObservation(), "thread B has no current observation before the call"); + // non-convenient transaction: the error is recorded and the span is closed and ended + transactionSpan.handleTransactionSpanError(new RuntimeException("boom")); + assertNull(registry.getCurrentObservation(), "handling the error on thread B must not make the span current there"); + }).get(); // surface thread B's failures on this thread + } finally { + threadB.shutdown(); + } + + assertSame(transactionObservation, registry.getCurrentObservation(), + "thread A's current observation is still the transaction span, even though it has ended"); + + // Test cleanup only, not a recommended pattern: this second call pops thread A's scope and stops the + // already-stopped observation again. + assertDoesNotThrow(() -> transactionSpan.spanFinalizing(true), "stopping a stopped observation must not throw"); + assertNull(registry.getCurrentObservation(), "cleanup must leave no scope open on the opening thread"); + } + + private static TracingManager tracingManager(final ObservationRegistry registry) { + return new TracingManager(ObservabilitySettings.micrometerBuilder() + .observationRegistry(registry) + .build()); + } + + /** + * A real (non-no-op) registry without the {@code TestObservationRegistry} validator. The validator rejects a + * second {@code stop()} of the same observation, which the cleanup in the cross-thread tests deliberately + * performs; a real registry treats it as a no-op, as asserted here. + */ + private static ObservationRegistry realObservationRegistry() { + ObservationRegistry registry = ObservationRegistry.create(); + registry.observationConfig().observationHandler(context -> true); + return registry; + } +} From 4c322d03dab5eddb9a72603231dce60364c1e5a0 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Sun, 15 Nov 2026 18:00:52 +0000 Subject: [PATCH 14/36] JAVA-5734 Assert the transaction span ends when finalized on another thread --- .../micrometer/TransactionSpan.java | 5 +-- .../micrometer/TransactionSpanScopeTest.java | 31 ++++++++++++++----- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java index 92da86fadd..7c8320a5ee 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java @@ -22,7 +22,8 @@ * State class for transaction tracing. *

* The scope opened by {@link #openScope()} is bound to the thread that opened it and must be closed on that same - * thread, via {@link #finalizeTransactionSpan}, {@link #handleTransactionSpanError} or {@link #spanFinalizing}. + * thread by {@link #finalizeTransactionSpan}, {@link #handleTransactionSpanError} or {@link #spanFinalizing} + * (for non-convenient transactions; convenient transactions close only via {@code spanFinalizing}). * Committing or aborting the transaction on a different thread makes the close a no-op there and leaves the * opening thread's current observation set to the transaction span after it has ended. A follow-up will revisit * the transaction scope lifetime. @@ -124,7 +125,7 @@ public TraceContext getContext() { * Must only be called from the sync driver where open and close happen on the same thread. *

* The scope is thread-bound: it must be closed on the same thread that opened it. Closing it from another - * thread is a no-op there and leaves this thread's current observation as the (ended) transaction span. + * thread is a no-op there and leaves the opening thread's current observation as the (ended) transaction span. * A follow-up will revisit the transaction scope lifetime. */ public void openScope() { diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanScopeTest.java index b22deb0dd9..0df657f67c 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanScopeTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanScopeTest.java @@ -19,12 +19,14 @@ import com.mongodb.observability.ObservabilitySettings; import com.mongodb.observability.micrometer.MongodbObservation; import io.micrometer.observation.Observation; +import io.micrometer.observation.ObservationHandler; import io.micrometer.observation.ObservationRegistry; import io.micrometer.observation.tck.TestObservationRegistry; import org.junit.jupiter.api.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -60,7 +62,8 @@ void openAndFinalizeOnTheSameThreadRestoreThePreviousObservation() { @Test void finalizeOnAnotherThreadIsANoOpThereAndLeavesTheOpenerScopeCurrent() throws Exception { - ObservationRegistry registry = realObservationRegistry(); + AtomicInteger stopCount = new AtomicInteger(); + ObservationRegistry registry = realObservationRegistry(stopCount); TransactionSpan transactionSpan = new TransactionSpan(tracingManager(registry)); transactionSpan.openScope(); // thread A (this thread) opens the scope @@ -81,8 +84,9 @@ void finalizeOnAnotherThreadIsANoOpThereAndLeavesTheOpenerScopeCurrent() throws threadB.shutdown(); } + assertEquals(1, stopCount.get(), "finalizing on thread B must end the transaction span exactly once"); assertSame(transactionObservation, registry.getCurrentObservation(), - "thread A's current observation is still the transaction span, even though it has ended"); + "thread A's current observation is still the (ended) transaction span"); // Test cleanup only, not a recommended pattern: this second call pops thread A's scope and stops the // already-stopped observation again. @@ -92,7 +96,8 @@ void finalizeOnAnotherThreadIsANoOpThereAndLeavesTheOpenerScopeCurrent() throws @Test void handleTransactionSpanErrorOnAnotherThreadBehavesTheSame() throws Exception { - ObservationRegistry registry = realObservationRegistry(); + AtomicInteger stopCount = new AtomicInteger(); + ObservationRegistry registry = realObservationRegistry(stopCount); TransactionSpan transactionSpan = new TransactionSpan(tracingManager(registry)); transactionSpan.openScope(); // thread A (this thread) opens the scope @@ -113,8 +118,9 @@ void handleTransactionSpanErrorOnAnotherThreadBehavesTheSame() throws Exception threadB.shutdown(); } + assertEquals(1, stopCount.get(), "handling the error on thread B must end the transaction span exactly once"); assertSame(transactionObservation, registry.getCurrentObservation(), - "thread A's current observation is still the transaction span, even though it has ended"); + "thread A's current observation is still the (ended) transaction span"); // Test cleanup only, not a recommended pattern: this second call pops thread A's scope and stops the // already-stopped observation again. @@ -131,11 +137,22 @@ private static TracingManager tracingManager(final ObservationRegistry registry) /** * A real (non-no-op) registry without the {@code TestObservationRegistry} validator. The validator rejects a * second {@code stop()} of the same observation, which the cleanup in the cross-thread tests deliberately - * performs; a real registry treats it as a no-op, as asserted here. + * performs; a real registry treats it as a no-op, as asserted here. The registered handler also counts + * {@code onStop} calls so the tests can assert that the span actually ended. */ - private static ObservationRegistry realObservationRegistry() { + private static ObservationRegistry realObservationRegistry(final AtomicInteger stopCount) { ObservationRegistry registry = ObservationRegistry.create(); - registry.observationConfig().observationHandler(context -> true); + registry.observationConfig().observationHandler(new ObservationHandler() { + @Override + public void onStop(final Observation.Context context) { + stopCount.incrementAndGet(); + } + + @Override + public boolean supportsContext(final Observation.Context context) { + return true; + } + }); return registry; } } From f46c1c15cff236599a02957ab1b94cc56dbd3a7f Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Sun, 15 Nov 2026 19:25:42 +0000 Subject: [PATCH 15/36] JAVA-5734 Do not hold the transaction span scope across user calls ClientSessionImpl.startTransaction() opened a scope on the transaction span and kept it open until commit, abort or the end of withTransaction. A scope is thread-bound: when the transaction was committed or aborted on another thread the close was a no-op there, and the starting thread kept the ended transaction span as its current observation. The held scope is not needed. Operation spans run inside a transaction are already parented explicitly on the transaction span through TransactionSpan.getContext() (TracingManager.createOperationSpan), and driver log lines emit inside the operation span scope. The transaction span is now never made current: TransactionSpan.openScope() and its closeScope() calls are removed, so the span may be started, finalized and errored from any thread. TransactionSpanScopeTest, which pinned the old cross-thread behaviour, is replaced by TransactionSpanTest covering the new contract. Behaviour change: sync user code running between driver calls inside a transaction no longer sees the MongoDB transaction span as the current span. User log lines there are no longer attributed to it, and user-created spans there are no longer auto-parented under it. Driver spans and driver log lines are unaffected. --- .../micrometer/TransactionSpan.java | 24 +-- .../micrometer/TransactionSpanScopeTest.java | 158 ---------------- .../micrometer/TransactionSpanTest.java | 169 ++++++++++++++++++ .../client/internal/ClientSessionImpl.java | 1 - 4 files changed, 172 insertions(+), 180 deletions(-) delete mode 100644 driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanScopeTest.java create mode 100644 driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanTest.java diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java index 7c8320a5ee..38fe6123e5 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java @@ -21,12 +21,9 @@ /** * State class for transaction tracing. *

- * The scope opened by {@link #openScope()} is bound to the thread that opened it and must be closed on that same - * thread by {@link #finalizeTransactionSpan}, {@link #handleTransactionSpanError} or {@link #spanFinalizing} - * (for non-convenient transactions; convenient transactions close only via {@code spanFinalizing}). - * Committing or aborting the transaction on a different thread makes the close a no-op there and leaves the - * opening thread's current observation set to the transaction span after it has ended. A follow-up will revisit - * the transaction scope lifetime. + * The transaction span is never made the current observation. Operation spans run inside the transaction are + * parented on it explicitly through {@link #getContext()}. Because no scope is held, the span may be started, + * finalized and errored from any thread. * * @since 5.7 */ @@ -61,7 +58,6 @@ public void handleTransactionSpanError(final Throwable e) { } if (!isConvenientTransaction) { - span.closeScope(); span.end(); } } @@ -75,7 +71,6 @@ public void finalizeTransactionSpan(final String status) { span.event(status); // clear previous commit error if any if (!isConvenientTransaction) { - span.closeScope(); span.end(); } reportedError = null; // clear previous commit error if any @@ -91,7 +86,6 @@ public void spanFinalizing(final boolean cleanupTransactionContext) { if (reportedError != null) { span.error(reportedError); } - span.closeScope(); span.end(); reportedError = null; // Don't clean up transaction context if we're still retrying (we want the retries to fold under the original transaction span) @@ -119,16 +113,4 @@ public void setIsConvenientTransaction() { public TraceContext getContext() { return span.context(); } - - /** - * Opens a scope for the transaction span, making it the current observation on the thread. - * Must only be called from the sync driver where open and close happen on the same thread. - *

- * The scope is thread-bound: it must be closed on the same thread that opened it. Closing it from another - * thread is a no-op there and leaves the opening thread's current observation as the (ended) transaction span. - * A follow-up will revisit the transaction scope lifetime. - */ - public void openScope() { - span.openScope(); - } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanScopeTest.java deleted file mode 100644 index 0df657f67c..0000000000 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanScopeTest.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.internal.observability.micrometer; - -import com.mongodb.observability.ObservabilitySettings; -import com.mongodb.observability.micrometer.MongodbObservation; -import io.micrometer.observation.Observation; -import io.micrometer.observation.ObservationHandler; -import io.micrometer.observation.ObservationRegistry; -import io.micrometer.observation.tck.TestObservationRegistry; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; - -/** - * Pins the thread-bound lifetime of the scope opened by {@link TransactionSpan#openScope()}. - *

- * {@link MicrometerTracer.MicrometerSpan} tracks open scopes per thread, so committing or aborting a transaction - * on a thread other than the one that started it does not restore the opening thread's previous observation. This - * is pre-existing behaviour that a follow-up will revisit; these tests make it explicit instead of accidental. - */ -class TransactionSpanScopeTest { - - @Test - void openAndFinalizeOnTheSameThreadRestoreThePreviousObservation() { - TestObservationRegistry registry = TestObservationRegistry.create(); - TransactionSpan transactionSpan = new TransactionSpan(tracingManager(registry)); - - assertNull(registry.getCurrentObservation(), "no observation is current before the transaction starts"); - - transactionSpan.openScope(); - Observation current = registry.getCurrentObservation(); - assertNotNull(current, "the transaction span must be the current observation on the opening thread"); - assertEquals(MongodbObservation.MONGODB_TRANSACTION.getName(), current.getContext().getName(), - "the current observation must be the transaction observation"); - - transactionSpan.finalizeTransactionSpan("COMMITTED"); - assertNull(registry.getCurrentObservation(), "finalizing on the opening thread must close its scope"); - } - - @Test - void finalizeOnAnotherThreadIsANoOpThereAndLeavesTheOpenerScopeCurrent() throws Exception { - AtomicInteger stopCount = new AtomicInteger(); - ObservationRegistry registry = realObservationRegistry(stopCount); - TransactionSpan transactionSpan = new TransactionSpan(tracingManager(registry)); - - transactionSpan.openScope(); // thread A (this thread) opens the scope - Observation transactionObservation = registry.getCurrentObservation(); - assertNotNull(transactionObservation); - assertEquals(MongodbObservation.MONGODB_TRANSACTION.getName(), - transactionObservation.getContext().getName()); - - ExecutorService threadB = Executors.newSingleThreadExecutor(); - try { - threadB.submit(() -> { - assertNull(registry.getCurrentObservation(), "thread B has no current observation before the call"); - transactionSpan.finalizeTransactionSpan("COMMITTED"); - // closeScope() is per-thread: thread B has no scope of its own to pop, so the close is a no-op there. - assertNull(registry.getCurrentObservation(), "finalizing on thread B must not make the span current there"); - }).get(); // surface thread B's failures on this thread - } finally { - threadB.shutdown(); - } - - assertEquals(1, stopCount.get(), "finalizing on thread B must end the transaction span exactly once"); - assertSame(transactionObservation, registry.getCurrentObservation(), - "thread A's current observation is still the (ended) transaction span"); - - // Test cleanup only, not a recommended pattern: this second call pops thread A's scope and stops the - // already-stopped observation again. - assertDoesNotThrow(() -> transactionSpan.spanFinalizing(true), "stopping a stopped observation must not throw"); - assertNull(registry.getCurrentObservation(), "cleanup must leave no scope open on the opening thread"); - } - - @Test - void handleTransactionSpanErrorOnAnotherThreadBehavesTheSame() throws Exception { - AtomicInteger stopCount = new AtomicInteger(); - ObservationRegistry registry = realObservationRegistry(stopCount); - TransactionSpan transactionSpan = new TransactionSpan(tracingManager(registry)); - - transactionSpan.openScope(); // thread A (this thread) opens the scope - Observation transactionObservation = registry.getCurrentObservation(); - assertNotNull(transactionObservation); - assertEquals(MongodbObservation.MONGODB_TRANSACTION.getName(), - transactionObservation.getContext().getName()); - - ExecutorService threadB = Executors.newSingleThreadExecutor(); - try { - threadB.submit(() -> { - assertNull(registry.getCurrentObservation(), "thread B has no current observation before the call"); - // non-convenient transaction: the error is recorded and the span is closed and ended - transactionSpan.handleTransactionSpanError(new RuntimeException("boom")); - assertNull(registry.getCurrentObservation(), "handling the error on thread B must not make the span current there"); - }).get(); // surface thread B's failures on this thread - } finally { - threadB.shutdown(); - } - - assertEquals(1, stopCount.get(), "handling the error on thread B must end the transaction span exactly once"); - assertSame(transactionObservation, registry.getCurrentObservation(), - "thread A's current observation is still the (ended) transaction span"); - - // Test cleanup only, not a recommended pattern: this second call pops thread A's scope and stops the - // already-stopped observation again. - assertDoesNotThrow(() -> transactionSpan.spanFinalizing(true), "stopping a stopped observation must not throw"); - assertNull(registry.getCurrentObservation(), "cleanup must leave no scope open on the opening thread"); - } - - private static TracingManager tracingManager(final ObservationRegistry registry) { - return new TracingManager(ObservabilitySettings.micrometerBuilder() - .observationRegistry(registry) - .build()); - } - - /** - * A real (non-no-op) registry without the {@code TestObservationRegistry} validator. The validator rejects a - * second {@code stop()} of the same observation, which the cleanup in the cross-thread tests deliberately - * performs; a real registry treats it as a no-op, as asserted here. The registered handler also counts - * {@code onStop} calls so the tests can assert that the span actually ended. - */ - private static ObservationRegistry realObservationRegistry(final AtomicInteger stopCount) { - ObservationRegistry registry = ObservationRegistry.create(); - registry.observationConfig().observationHandler(new ObservationHandler() { - @Override - public void onStop(final Observation.Context context) { - stopCount.incrementAndGet(); - } - - @Override - public boolean supportsContext(final Observation.Context context) { - return true; - } - }); - return registry; - } -} diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanTest.java new file mode 100644 index 0000000000..d980c7074c --- /dev/null +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanTest.java @@ -0,0 +1,169 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.observability.micrometer; + +import com.mongodb.MongoNamespace; +import com.mongodb.ReadConcern; +import com.mongodb.internal.IgnorableRequestContext; +import com.mongodb.internal.TimeoutContext; +import com.mongodb.internal.TimeoutSettings; +import com.mongodb.internal.connection.OperationContext; +import com.mongodb.internal.connection.ReadConcernAwareNoOpSessionContext; +import com.mongodb.observability.ObservabilitySettings; +import com.mongodb.observability.micrometer.MongodbObservation; +import io.micrometer.observation.Observation; +import io.micrometer.observation.ObservationHandler; +import io.micrometer.observation.ObservationRegistry; +import io.micrometer.observation.ObservationView; +import io.micrometer.observation.tck.TestObservationRegistry; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +/** + * The transaction span is never made the current observation, so it can be started, finalized and errored on any + * thread without leaving a scope behind; operation spans are parented on it explicitly through + * {@link TransactionSpan#getContext()}. + */ +class TransactionSpanTest { + + @Test + void creatingATransactionSpanDoesNotMakeItCurrent() { + TestObservationRegistry registry = TestObservationRegistry.create(); + AtomicInteger stopCount = countStops(registry); + TransactionSpan transactionSpan = new TransactionSpan(tracingManager(registry)); + + assertNull(registry.getCurrentObservation(), "creating the transaction span must not make it current"); + + transactionSpan.finalizeTransactionSpan("COMMITTED"); + assertEquals(1, stopCount.get(), "finalizing must end the transaction span exactly once"); + assertNull(registry.getCurrentObservation(), "finalizing must leave no observation current"); + } + + @Test + void finalizeOnAnotherThreadEndsTheSpanAndLeavesNoScopeOnEitherThread() throws Exception { + TestObservationRegistry registry = TestObservationRegistry.create(); + AtomicInteger stopCount = countStops(registry); + TransactionSpan transactionSpan = new TransactionSpan(tracingManager(registry)); // thread A (this thread) + + ExecutorService threadB = Executors.newSingleThreadExecutor(); + try { + threadB.submit(() -> { + transactionSpan.finalizeTransactionSpan("COMMITTED"); + assertNull(registry.getCurrentObservation(), "finalizing on thread B must leave no observation current there"); + }).get(); // surface thread B's failures on this thread + } finally { + threadB.shutdown(); + } + + assertEquals(1, stopCount.get(), "finalizing on thread B must end the transaction span exactly once"); + assertNull(registry.getCurrentObservation(), "thread A must have no observation current"); + } + + @Test + void handleTransactionSpanErrorOnAnotherThreadBehavesTheSame() throws Exception { + TestObservationRegistry registry = TestObservationRegistry.create(); + AtomicInteger stopCount = countStops(registry); + TransactionSpan transactionSpan = new TransactionSpan(tracingManager(registry)); // thread A (this thread) + + ExecutorService threadB = Executors.newSingleThreadExecutor(); + try { + threadB.submit(() -> { + // non-convenient transaction: the error is recorded and the span is ended + transactionSpan.handleTransactionSpanError(new RuntimeException("boom")); + assertNull(registry.getCurrentObservation(), "handling the error on thread B must leave no observation current there"); + }).get(); // surface thread B's failures on this thread + } finally { + threadB.shutdown(); + } + + assertEquals(1, stopCount.get(), "handling the error on thread B must end the transaction span exactly once"); + assertNull(registry.getCurrentObservation(), "thread A must have no observation current"); + } + + @Test + void operationSpanCreatedInsideTransactionIsParentedOnTheTransactionSpan() { + TestObservationRegistry registry = TestObservationRegistry.create(); + List startedContexts = new CopyOnWriteArrayList<>(); + registry.observationConfig().observationHandler(new ObservationHandler() { + @Override + public void onStart(final Observation.Context context) { + startedContexts.add(context); + } + + @Override + public boolean supportsContext(final Observation.Context context) { + return true; + } + }); + TracingManager tracingManager = tracingManager(registry); + TransactionSpan transactionSpan = new TransactionSpan(tracingManager); + OperationContext operationContext = new OperationContext(IgnorableRequestContext.INSTANCE, + new ReadConcernAwareNoOpSessionContext(ReadConcern.DEFAULT), new TimeoutContext(TimeoutSettings.DEFAULT), null); + + Span operationSpan = tracingManager.createOperationSpan(transactionSpan, operationContext, "insert", + new MongoNamespace("db.coll")); + assertNotNull(operationSpan); + + assertEquals(2, startedContexts.size(), "the transaction and operation observations must have started"); + Observation.Context transactionContext = startedContexts.get(0); + Observation.Context operationContextView = startedContexts.get(1); + assertEquals(MongodbObservation.MONGODB_TRANSACTION.getName(), transactionContext.getName()); + assertEquals(MongodbObservation.MONGODB_OPERATION.getName(), operationContextView.getName()); + ObservationView parent = operationContextView.getParentObservation(); + assertNotNull(parent, "the operation observation must have a parent"); + assertSame(transactionContext, parent.getContextView(), "the operation observation must be parented on the transaction"); + + operationSpan.end(); + transactionSpan.finalizeTransactionSpan("COMMITTED"); + assertNull(registry.getCurrentObservation(), "no observation must remain current"); + } + + private static TracingManager tracingManager(final ObservationRegistry registry) { + return new TracingManager(ObservabilitySettings.micrometerBuilder() + .observationRegistry(registry) + .build()); + } + + /** + * Registers a handler that counts {@code onStop} calls so the tests can assert that the span actually ended. + */ + private static AtomicInteger countStops(final ObservationRegistry registry) { + AtomicInteger stopCount = new AtomicInteger(); + registry.observationConfig().observationHandler(new ObservationHandler() { + @Override + public void onStop(final Observation.Context context) { + stopCount.incrementAndGet(); + } + + @Override + public boolean supportsContext(final Observation.Context context) { + return true; + } + }); + return stopCount; + } +} diff --git a/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java index d2d6720edd..482213b159 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java @@ -201,7 +201,6 @@ private void startTransaction(final TransactionOptions transactionOptions, final if (tracingManager.isEnabled()) { transactionSpan = new TransactionSpan(tracingManager); - transactionSpan.openScope(); } clearTransactionContext(); setTimeoutContext(timeoutContext); From feeee2d05942a0c6e6a186c02fe97ee203f280df Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Mon, 16 Nov 2026 00:39:31 +0000 Subject: [PATCH 16/36] JAVA-5734 Update log correlation prose tests to specifications PR 2008 (2026-11-16) --- .../observability/MicrometerProseTest.java | 9 + .../client/AbstractMicrometerProseTest.java | 169 ++++++++++++++---- 2 files changed, 142 insertions(+), 36 deletions(-) diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/observability/MicrometerProseTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/observability/MicrometerProseTest.java index c58bb98f2c..f45aeed1aa 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/observability/MicrometerProseTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/observability/MicrometerProseTest.java @@ -18,6 +18,7 @@ import com.mongodb.MongoClientSettings; import com.mongodb.client.AbstractMicrometerProseTest; +import com.mongodb.client.ClientSession; import com.mongodb.client.MongoClient; import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient; @@ -29,4 +30,12 @@ public class MicrometerProseTest extends AbstractMicrometerProseTest { protected MongoClient createMongoClient(final MongoClientSettings settings) { return new SyncMongoClient(settings); } + + @Override + protected void runInTransaction(final ClientSession session, final Runnable body) { + // the reactive driver has no withTransaction, so start and commit the transaction explicitly + session.startTransaction(); + body.run(); + session.commitTransaction(); + } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java index 22669ef49a..1d8d125f7b 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java @@ -16,7 +16,10 @@ package com.mongodb.client; +import com.mongodb.AuthenticationMechanism; import com.mongodb.MongoClientSettings; +import com.mongodb.MongoCredential; +import com.mongodb.MongoException; import com.mongodb.MongoTimeoutException; import com.mongodb.ServerAddress; import com.mongodb.internal.EnvironmentProvider; @@ -29,6 +32,8 @@ import com.mongodb.observability.ObservabilitySettings; import com.mongodb.client.observability.SpanTree; import com.mongodb.client.observability.SpanTree.SpanNode; +import com.mongodb.connection.ClusterConnectionMode; +import com.mongodb.connection.ClusterSettings; import com.mongodb.observability.micrometer.MicrometerObservabilitySettings; import io.micrometer.common.KeyValues; import io.micrometer.observation.Observation; @@ -59,6 +64,7 @@ import java.util.stream.Collectors; import static com.mongodb.ClusterFixture.getConnectionString; +import static com.mongodb.ClusterFixture.getCredential; import static com.mongodb.ClusterFixture.getDefaultDatabaseName; import static com.mongodb.ClusterFixture.getPrimary; import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet; @@ -447,14 +453,14 @@ public KeyValues getLowCardinalityKeyValues(final MongodbObservationContext cont @DisplayName("Test 10: Command log messages carry their own command span") @Test void testCommandLogMessagesCarryTheirOwnCommandSpan() { - // the retry on error code 91 requires retryable reads, which need a replica set or a sharded cluster + // the fail point is scoped by appName, which requires MongoDB 4.4; on a sharded cluster the fixture URI names one mongos assumeTrue(serverVersionAtLeast(4, 4)); - assumeTrue(isDiscoverableReplicaSet() || isSharded()); String appName = "otel-log-test10"; BsonDocument failPoint = BsonDocument.parse("{ configureFailPoint: 'failCommand', mode: { times: 1 }," + " data: { failCommands: ['find'], errorCode: 91, appName: '" + appName + "' } }"); // error code 91 marks the server Unknown; a short heartbeat lets the retry rediscover it quickly MongoClientSettings settings = MongoClientSettings.builder(tracedSettings(appName)) + .retryReads(true) .applyToServerSettings(b -> b.heartbeatFrequency(500, TimeUnit.MILLISECONDS)) .build(); try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); @@ -491,19 +497,18 @@ void testCommandLogMessagesCarryTheirOwnCommandSpan() { } } - @DisplayName("Test 11: Operation-path log messages carry the operation span") + @DisplayName("Test 11 (steps 1-3): Operation-path log messages carry the operation span") @Test void testOperationPathLogMessagesCarryTheOperationSpan() { + assumeFalse(isLoadBalanced()); String operationName = "insert " + getDefaultDatabaseName() + ".test"; String appName = "otel-log-test11"; - String succeedingTraceId; try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); MongoClient client = createMongoClient(tracedSettings(appName))) { client.getDatabase(getDefaultDatabaseName()).getCollection("test").insertOne(new Document("x", 1)); assertNoSpanIsCurrent(); FinishedSpan operation = spanNamed(inMemoryOtel.getFinishedSpans(), operationName, 0); - succeedingTraceId = operation.getTraceId(); for (String messageId : asList("Server selection started", "Server selection succeeded", "Connection checkout started", "Connection checked out", "Connection checked in")) { List observed = logs.messages(messageId).stream() @@ -514,28 +519,31 @@ void testOperationPathLogMessagesCarryTheOperationSpan() { } } } + } - // a fixed localhost host list is incompatible with an SRV fixture, and a load-balanced fixture would not time out + @DisplayName("Test 11 (steps 4-6): Server selection failure log messages carry the operation span") + @Test + void testServerSelectionFailureLogMessagesCarryTheOperationSpan() { + // a load-balanced fixture would not time out; the SRV assumption keeps the fixture's resolver settings out of the way assumeFalse(getConnectionString().isSrvProtocol()); assumeFalse(isLoadBalanced()); - - String failingAppName = "otel-log-test11-failing"; - MongoClientSettings failing = MongoClientSettings.builder(tracedSettings(failingAppName)) - .applyToClusterSettings(b -> b.hosts(singletonList(new ServerAddress("localhost", 1))) - .serverSelectionTimeout(500, TimeUnit.MILLISECONDS)) + String operationName = "insert " + getDefaultDatabaseName() + ".test"; + String appName = "otel-log-test11-failing"; + // replace the fixture's cluster settings entirely so that the host list does not depend on the fixture URI's shape + MongoClientSettings failing = MongoClientSettings.builder(tracedSettings(appName)) + .applyToClusterSettings(b -> b.applySettings(ClusterSettings.builder() + .hosts(singletonList(new ServerAddress("localhost", 1))) + .mode(ClusterConnectionMode.SINGLE) + .serverSelectionTimeout(500, TimeUnit.MILLISECONDS) + .build())) .build(); - try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(failingAppName, inMemoryOtel.getTracer()); + try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); MongoClient client = createMongoClient(failing)) { assertThrows(MongoTimeoutException.class, () -> client.getDatabase(getDefaultDatabaseName()).getCollection("test").insertOne(new Document("x", 1))); assertNoSpanIsCurrent(); - // the failing operation is the only one outside the trace of the succeeding operation above - List failingOperations = inMemoryOtel.getFinishedSpans().stream() - .filter(s -> s.getName().equals(operationName) && !s.getTraceId().equals(succeedingTraceId)) - .collect(Collectors.toList()); - assertEquals(1, failingOperations.size(), "expected one failing operation span but got " + failingOperations); - FinishedSpan operation = failingOperations.get(0); + FinishedSpan operation = onlySpanNamed(inMemoryOtel.getFinishedSpans(), operationName); for (String messageId : asList("Waiting for suitable server to become available", "Server selection failed")) { List observed = logs.messages(messageId); assertFalse(observed.isEmpty(), messageId + " must be emitted"); @@ -547,7 +555,44 @@ void testOperationPathLogMessagesCarryTheOperationSpan() { } } - @DisplayName("Test 12: Command log messages inside a transaction carry the command span and the transaction's trace") + @DisplayName("Test 11 (steps 7-10): Connection checkout failure log messages carry the operation span") + @Test + void testConnectionCheckoutFailureLogMessagesCarryTheOperationSpan() { + assumeFalse(isLoadBalanced()); + // only SCRAM sends saslContinue as a standalone command; a null mechanism negotiates SCRAM + MongoCredential credential = getCredential(); + assumeTrue(credential != null); + assumeTrue(credential.getAuthenticationMechanism() == null + || credential.getAuthenticationMechanism() == AuthenticationMechanism.SCRAM_SHA_1 + || credential.getAuthenticationMechanism() == AuthenticationMechanism.SCRAM_SHA_256); + // the fail point is scoped by appName, which requires MongoDB 4.4 + assumeTrue(serverVersionAtLeast(4, 4)); + String appName = "otel-log-test11-checkout-failing"; + BsonDocument failPoint = BsonDocument.parse("{ configureFailPoint: 'failCommand', mode: { times: 1 }," + + " data: { failCommands: ['saslContinue'], closeConnection: true, appName: '" + appName + "' } }"); + MongoClientSettings settings = MongoClientSettings.builder(tracedSettings(appName)) + .retryReads(false) + .applyToServerSettings(b -> b.heartbeatFrequency(10, TimeUnit.SECONDS)) + .build(); + try (FailPoint ignored = FailPoint.enable(failPoint, getPrimary()); + SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); + MongoClient client = createMongoClient(settings)) { + assertThrows(MongoException.class, () -> client.getDatabase(getDefaultDatabaseName()).getCollection("test").find().first()); + assertNoSpanIsCurrent(); + + FinishedSpan operation = onlySpanNamed(inMemoryOtel.getFinishedSpans(), "find " + getDefaultDatabaseName() + ".test"); + for (String messageId : asList("Connection checkout started", "Connection checkout failed")) { + List observed = logs.messages(messageId); + assertFalse(observed.isEmpty(), messageId + " must be emitted"); + for (ObservedLog l : observed) { + assertEquals(operation.getTraceId(), l.traceId, messageId + " must carry the operation's trace"); + assertEquals(operation.getSpanId(), l.spanId, messageId + " must carry the operation span"); + } + } + } + } + + @DisplayName("Test 12: Log messages inside a transaction") @Test void testLogMessagesInsideTransaction() { assumeTrue(isDiscoverableReplicaSet() || isSharded()); @@ -556,15 +601,15 @@ void testLogMessagesInsideTransaction() { MongoClient client = createMongoClient(tracedSettings(appName)); ClientSession session = client.startSession()) { MongoCollection collection = client.getDatabase(getDefaultDatabaseName()).getCollection("test"); - // explicit start/commit rather than withTransaction, which the reactive sync adapter does not support - session.startTransaction(); - collection.insertOne(session, new Document("x", 1)); - session.commitTransaction(); + runInTransaction(session, () -> collection.insertOne(session, new Document("x", 1))); assertNoSpanIsCurrent(); List spans = inMemoryOtel.getFinishedSpans(); FinishedSpan transaction = spanNamed(spans, "transaction", 0); + FinishedSpan insertOperation = spanNamed(spans, "insert " + getDefaultDatabaseName() + ".test", 0); + assertEquals(transaction.getSpanId(), insertOperation.getParentId(), "the insert operation must run under the transaction"); FinishedSpan insertCommand = spanNamed(spans, "insert", 0); + assertEquals(insertOperation.getSpanId(), insertCommand.getParentId(), "the insert command must run under its operation"); FinishedSpan commitCommand = spanNamed(spans, "commitTransaction", 0); for (FinishedSpan command : asList(insertCommand, commitCommand)) { assertEquals(transaction.getTraceId(), command.getTraceId(), command.getName() + " must be in the transaction's trace"); @@ -588,14 +633,43 @@ void testLogMessagesInsideTransaction() { assertTrue(commandSpanIds.contains(l.spanId), l.messageId + " must carry a command span of the transaction"); } } + + // server selection and connection checkout precede any command span, so they belong to the operation span; every + // operation of the transaction (the insert and the commit) is a child of the transaction span + Set operationSpanIds = spans.stream() + .filter(s -> transaction.getSpanId().equals(s.getParentId())) + .map(FinishedSpan::getSpanId).collect(Collectors.toSet()); + for (String messageId : asList("Server selection started", "Server selection succeeded", + "Connection checkout started", "Connection checked out", "Connection checked in")) { + List observed = logs.messages(messageId).stream() + .filter(l -> transaction.getTraceId().equals(l.traceId)).collect(Collectors.toList()); + assertTrue(observed.stream().anyMatch(l -> insertOperation.getSpanId().equals(l.spanId)), + messageId + " must be emitted for the insert carrying the insert operation span, but got " + spanIds(observed)); + for (ObservedLog l : observed) { + assertNotEquals(transaction.getSpanId(), l.spanId, messageId + " must not carry the transaction span"); + assertTrue(operationSpanIds.contains(l.spanId), messageId + " must carry an operation span of the transaction"); + } + } } } - // Test 14 (trace context fields in structured log messages) does not apply to Java: the driver logs through SLF4J and - // adds no trace fields of its own. + /** + * Runs {@code body} in a transaction on {@code session}, as the spec's {@code withTransaction} step requires. + */ + protected void runInTransaction(final ClientSession session, final Runnable body) { + session.withTransaction(() -> { + body.run(); + return null; + }); + } + + // Tests 14 and 15 apply only to driver-managed log output and are not applicable to Java: the driver logs through SLF4J and + // has no driver-managed log destinations. The reactive subclass runs Tests 10 to 13 as the asynchronous API. @DisplayName("Test 13: Background log messages are not attributed to an operation") @Test void testBackgroundLogMessagesAreNotAttributedToAnOperation() throws InterruptedException { + // load-balanced clients start no monitoring connection, so they emit no heartbeat messages + assumeFalse(isLoadBalanced()); String appName = "otel-log-test13"; MongoClientSettings settings = MongoClientSettings.builder(tracedSettings(appName)) .applyToServerSettings(b -> b.heartbeatFrequency(100, TimeUnit.MILLISECONDS)) @@ -603,24 +677,37 @@ void testBackgroundLogMessagesAreNotAttributedToAnOperation() throws Interrupted try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); MongoClient client = createMongoClient(settings)) { client.getDatabase(getDefaultDatabaseName()).getCollection("test").insertOne(new Document("x", 1)); + assertNoSpanIsCurrent(); int topologyMessagesBefore = logs.component(LogMessage.Component.TOPOLOGY).size(); - long deadline = System.currentTimeMillis() + 5_000; - while (logs.component(LogMessage.Component.TOPOLOGY).size() == topologyMessagesBefore - && System.currentTimeMillis() < deadline) { + + // a fixed delay is not sufficient: without a heartbeat message after the operation there is nothing to check + long deadline = System.currentTimeMillis() + 10_000; + while (!heartbeatSucceededSince(logs, topologyMessagesBefore) && System.currentTimeMillis() < deadline) { Thread.sleep(50); } - Set operationTraceIds = inMemoryOtel.getFinishedSpans().stream() - .map(FinishedSpan::getTraceId).collect(Collectors.toSet()); - assertFalse(operationTraceIds.isEmpty(), "the operation must have produced spans"); - List background = logs.component(LogMessage.Component.TOPOLOGY); - assertTrue(background.size() > topologyMessagesBefore, "a heartbeat message must have been logged after the operation"); - for (ObservedLog l : background) { - assertFalse(l.traceId != null && operationTraceIds.contains(l.traceId), - l.messageId + " must not carry the trace of a driver operation"); + assertTrue(heartbeatSucceededSince(logs, topologyMessagesBefore), + "a \"Server heartbeat succeeded\" message must have been logged after the operation"); + + FinishedSpan operation = spanNamed(inMemoryOtel.getFinishedSpans(), "insert " + getDefaultDatabaseName() + ".test", 0); + String operationTraceId = operation.getTraceId(); + Set operationSpanIds = inMemoryOtel.getFinishedSpans().stream() + .filter(s -> operationTraceId.equals(s.getTraceId())) + .map(FinishedSpan::getSpanId).collect(Collectors.toSet()); + List topology = logs.component(LogMessage.Component.TOPOLOGY); + for (ObservedLog l : topology.subList(topologyMessagesBefore, topology.size())) { + assertNotEquals(operationTraceId, l.traceId, l.messageId + " must not carry the operation's trace"); + assertFalse(l.spanId != null && operationSpanIds.contains(l.spanId), + l.messageId + " must not carry a span of the operation"); } } } + private static boolean heartbeatSucceededSince(final SpanRecordingInterceptor logs, final int topologyMessagesBefore) { + List topology = logs.component(LogMessage.Component.TOPOLOGY); + return topology.subList(topologyMessagesBefore, topology.size()).stream() + .anyMatch(l -> l.messageId.equals("Server heartbeat succeeded")); + } + private MongoClientSettings tracedSettings(final String applicationName) { // tracing is enabled by default; clear any override left by another test environmentOverride.set(ENV_OBSERVABILITY_ENABLED, null); @@ -643,6 +730,16 @@ private static FinishedSpan spanNamed(final List spans, final Stri return matching.get(index); } + private static FinishedSpan onlySpanNamed(final List spans, final String name) { + List matching = spans.stream().filter(s -> s.getName().equals(name)).collect(Collectors.toList()); + assertEquals(1, matching.size(), "expected exactly one span named " + name + " but got " + matching); + return matching.get(0); + } + + private static List spanIds(final List logs) { + return logs.stream().map(l -> l.spanId).collect(Collectors.toList()); + } + /** Trace id and span id that were current on the thread when a log message was emitted. */ private static final class ObservedLog { private final String messageId; From 3f65e6892d6a8adb7589d4e57b21c81182d4fe51 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Wed, 25 Nov 2026 16:40:16 +0000 Subject: [PATCH 17/36] JAVA-5734 Explain why MicrometerSpan keeps a per-thread scope stack --- .../internal/observability/micrometer/MicrometerTracer.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java index 676bf462cb..da4f4daa7d 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java @@ -244,6 +244,10 @@ static class MicrometerSpan implements Span { @Nullable private final MongoNamespace namespace; private final int queryTextLength; + // Open scopes of this span, per thread. A Micrometer scope is thread-local state, and in the async driver + // the same span is made current from several threads (e.g. the operation span from the caller thread, a + // Netty thread and the cluster thread as each one logs). Each thread must close only the scopes it opened, + // and a thread may hold more than one at a time when a log site re-enters a scope that is already open. private final ThreadLocal> scopes = new ThreadLocal<>(); /** @@ -284,7 +288,6 @@ public void closeScope() { } } - // visible for testing boolean isThreadLocalEmpty() { return scopes.get() == null; } From f43f5270e410196c25e2451aeac3ac7123487bec Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Wed, 25 Nov 2026 17:12:14 +0000 Subject: [PATCH 18/36] JAVA-5734 Clarify that every openScope must be matched by a closeScope --- .../com/mongodb/internal/observability/micrometer/Span.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java index 69da7633ad..45a293343a 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java @@ -90,9 +90,9 @@ public MongodbObservationContext getMongodbObservationContext() { /** * Opens a scope for this span, making it the current observation on the calling thread. - * A successful {@code openScope()} must be followed by a {@link #closeScope()} on the same thread. - * Scopes nest per thread: each {@code openScope()} may be paired with a {@link #closeScope()} - * on the same thread, and calling {@code openScope()} after {@link #end()} does not throw. + * Every successful {@code openScope()} must be matched by a {@link #closeScope()} on the same thread; + * scopes nest per thread, so a thread may open the scope again before closing it. + * Calling {@code openScope()} after {@link #end()} does not throw. */ void openScope(); From 519aab5f0fc0144daa1223f9c067ee16ace5a846 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Wed, 25 Nov 2026 17:29:28 +0000 Subject: [PATCH 19/36] JAVA-5734 Move runInScope onto the Span interface A one-method utility class next to the contract it enforces was more indirection than it was worth. Span.runInScope keeps the null handling and the try/finally close; call sites in BaseCluster and DefaultConnectionPool are updated and SpanScopes is removed. --- .../internal/connection/BaseCluster.java | 10 ++-- .../connection/DefaultConnectionPool.java | 9 ++-- .../observability/micrometer/Span.java | 21 ++++++++ .../observability/micrometer/SpanScopes.java | 48 ------------------- ...copesTest.java => SpanRunInScopeTest.java} | 10 ++-- 5 files changed, 35 insertions(+), 63 deletions(-) delete mode 100644 driver-core/src/main/com/mongodb/internal/observability/micrometer/SpanScopes.java rename driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/{SpanScopesTest.java => SpanRunInScopeTest.java} (90%) diff --git a/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java b/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java index 91f6a8ed74..73b28beedb 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java +++ b/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java @@ -41,7 +41,7 @@ import com.mongodb.internal.logging.LogMessage; import com.mongodb.internal.logging.LogMessage.Entry; import com.mongodb.internal.logging.StructuredLogger; -import com.mongodb.internal.observability.micrometer.SpanScopes; +import com.mongodb.internal.observability.micrometer.Span; import com.mongodb.internal.selector.AtMostTwoRandomServerSelector; import com.mongodb.internal.selector.LatencyMinimizingServerSelector; import com.mongodb.internal.selector.MinimumOperationCountServerSelector; @@ -564,7 +564,7 @@ static void logServerSelectionStarted( new Entry(SELECTOR, serverSelector.toString()), new Entry(TOPOLOGY_DESCRIPTION, clusterDescription.getShortDescription())), "Server selection started for operation[ {}] with ID {}. Selector: {}, topology description: {}"); - SpanScopes.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); + Span.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); } } @@ -588,7 +588,7 @@ static void logServerSelectionWaiting( new Entry(TOPOLOGY_DESCRIPTION, clusterDescription.getShortDescription())), "Waiting for server to become available for operation[ {}] with ID {}.[ Remaining time: {} ms.]" + " Selector: {}, topology description: {}."); - SpanScopes.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); + Span.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); } } @@ -614,7 +614,7 @@ static void logServerSelectionFailed( new Entry(SELECTOR, serverSelector.toString()), new Entry(TOPOLOGY_DESCRIPTION, clusterDescription.getShortDescription())), "Server selection failed for operation[ {}] with ID {}. Failure: {}. Selector: {}, topology description: {}"); - SpanScopes.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); + Span.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); } } @@ -636,7 +636,7 @@ static void logServerSelectionSucceeded( new Entry(TOPOLOGY_DESCRIPTION, clusterDescription.getShortDescription())), "Server selection succeeded for operation[ {}] with ID {}. Selected server: {}[:{}]." + " Selector: {}, topology description: {}"); - SpanScopes.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); + Span.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); } } diff --git a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java index 6340952c4c..6994d69dc9 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java +++ b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java @@ -53,7 +53,6 @@ import com.mongodb.internal.logging.LogMessage; import com.mongodb.internal.logging.StructuredLogger; import com.mongodb.internal.observability.micrometer.Span; -import com.mongodb.internal.observability.micrometer.SpanScopes; import com.mongodb.internal.thread.DaemonThreadFactory; import com.mongodb.internal.time.StartTime; import com.mongodb.internal.time.Timeout; @@ -279,7 +278,7 @@ private Throwable checkOutFailed(final Throwable t, final OperationContext opera entries.add(new LogMessage.Entry(REASON_DESCRIPTION, EventReasonMessageResolver.getMessage(reason))); entries.add(new LogMessage.Entry(ERROR_DESCRIPTION, reason == Reason.CONNECTION_ERROR ? result.toString() : null)); entries.add(new LogMessage.Entry(DURATION_MS, checkoutDuration.toMillis())); - SpanScopes.runInScope(operationContext.getTracingSpan(), + Span.runInScope(operationContext.getTracingSpan(), () -> logMessage("Connection checkout failed", clusterId, message, entries)); } connectionPoolListener.connectionCheckOutFailed( @@ -571,7 +570,7 @@ private void connectionCheckedOut( final List entries = createBasicEntries(); entries.add(new LogMessage.Entry(DRIVER_CONNECTION_ID, connectionId.getLocalValue())); entries.add(new LogMessage.Entry(DURATION_MS, checkoutDuration.toMillis())); - SpanScopes.runInScope(operationContext.getTracingSpan(), + Span.runInScope(operationContext.getTracingSpan(), () -> logMessage("Connection checked out", clusterId, "Connection checked out: address={}:{}, driver-generated ID={}, duration={} ms", entries)); } @@ -590,7 +589,7 @@ private void connectionCheckedOut( private StartTime connectionCheckoutStarted(final OperationContext operationContext) { StartTime checkoutStart = StartTime.now(); if (requiresLogging(serverId.getClusterId())) { - SpanScopes.runInScope(operationContext.getTracingSpan(), + Span.runInScope(operationContext.getTracingSpan(), () -> logEventMessage("Connection checkout started", "Checkout started for connection to {}:{}")); } @@ -688,7 +687,7 @@ public void close() { private void connectionCheckedIn() { ConnectionId connectionId = getId(wrapped); if (requiresLogging(serverId.getClusterId())) { - SpanScopes.runInScope(operationSpan, () -> logEventMessage("Connection checked in", + Span.runInScope(operationSpan, () -> logEventMessage("Connection checked in", "Connection checked in: address={}:{}, driver-generated ID={}", connectionId.getLocalValue())); } diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java index 45a293343a..0e81f6bfb6 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java @@ -156,4 +156,25 @@ public MongodbObservationContext getMongodbObservationContext() { */ @Nullable MongoNamespace getNamespace(); + + /** + * Runs an action while the span's scope is open on the calling thread, so that anything that reads the current + * tracing context during the action (log appenders, MDC bridges, listeners) observes that span. The scope is + * closed even if the action throws. + * + * @param span the span to make current, or {@code null} to run the action without touching any scope + * @param action the action to run + */ + static void runInScope(@Nullable final Span span, final Runnable action) { + if (span == null) { + action.run(); + return; + } + span.openScope(); + try { + action.run(); + } finally { + span.closeScope(); + } + } } diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/SpanScopes.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/SpanScopes.java deleted file mode 100644 index a9c3149c2c..0000000000 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/SpanScopes.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.internal.observability.micrometer; - -import com.mongodb.lang.Nullable; - -/** - * Runs an action while a {@link Span}'s scope is open on the current thread, so that anything that reads the - * current tracing context during the action (log appenders, MDC bridges, listeners) observes that span. - * - *

This class is not part of the public API and may be removed or changed at any time

- */ -public final class SpanScopes { - - /** - * @param span the span to make current, or {@code null} to run the action without touching any scope - * @param action the action to run - */ - public static void runInScope(@Nullable final Span span, final Runnable action) { - if (span == null) { - action.run(); - return; - } - span.openScope(); - try { - action.run(); - } finally { - span.closeScope(); - } - } - - private SpanScopes() { - } -} diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanScopesTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanRunInScopeTest.java similarity index 90% rename from driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanScopesTest.java rename to driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanRunInScopeTest.java index 72abff1836..74add206b8 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanScopesTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanRunInScopeTest.java @@ -29,19 +29,19 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -class SpanScopesTest { +class SpanRunInScopeTest { @Test void runsActionDirectlyWhenSpanIsNull() { List calls = new ArrayList<>(); - SpanScopes.runInScope(null, () -> calls.add("action")); + Span.runInScope(null, () -> calls.add("action")); assertEquals(asList("action"), calls); } @Test void opensScopeBeforeActionAndClosesAfter() { List calls = new ArrayList<>(); - SpanScopes.runInScope(new RecordingSpan(calls), () -> calls.add("action")); + Span.runInScope(new RecordingSpan(calls), () -> calls.add("action")); assertEquals(asList("open", "action", "close"), calls); } @@ -49,7 +49,7 @@ void opensScopeBeforeActionAndClosesAfter() { void closesScopeWhenActionThrows() { List calls = new ArrayList<>(); RuntimeException failure = new RuntimeException("appender failed"); - RuntimeException thrown = assertThrows(RuntimeException.class, () -> SpanScopes.runInScope(new RecordingSpan(calls), () -> { + RuntimeException thrown = assertThrows(RuntimeException.class, () -> Span.runInScope(new RecordingSpan(calls), () -> { throw failure; })); assertEquals(failure, thrown); @@ -60,7 +60,7 @@ void closesScopeWhenActionThrows() { void nestsScopes() { List calls = new ArrayList<>(); RecordingSpan span = new RecordingSpan(calls); - SpanScopes.runInScope(span, () -> SpanScopes.runInScope(span, () -> calls.add("action"))); + Span.runInScope(span, () -> Span.runInScope(span, () -> calls.add("action"))); assertEquals(asList("open", "open", "action", "close", "close"), calls); } From 8861ba778735239fe9c049d08d36a9f1d7be3318 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Wed, 25 Nov 2026 17:33:28 +0000 Subject: [PATCH 20/36] JAVA-5734 Simplify TracingScopedCommandEventSender javadoc --- .../internal/connection/TracingScopedCommandEventSender.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/driver-core/src/main/com/mongodb/internal/connection/TracingScopedCommandEventSender.java b/driver-core/src/main/com/mongodb/internal/connection/TracingScopedCommandEventSender.java index 40d56ae8de..6cbc3f0b7f 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/TracingScopedCommandEventSender.java +++ b/driver-core/src/main/com/mongodb/internal/connection/TracingScopedCommandEventSender.java @@ -19,9 +19,8 @@ import com.mongodb.internal.observability.micrometer.Span; /** - * Emits command events while the command span's scope is open on the emitting thread, so that command - * listeners and log appenders observe the command span (for example as {@code traceId}/{@code spanId} in - * the MDC). The scope is opened and closed around each event; {@link Span#closeScope()} is idempotent. + * A {@link CommandEventSender} for the asynchronous path that opens the command span's scope around each event, + * so command listeners and log appenders observe the command span on whichever thread emits the event. * *

This class is not part of the public API and may be removed or changed at any time

*/ From e5d55f5d8293e88b60d2a6a15e922b735a47df34 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Wed, 25 Nov 2026 17:37:26 +0000 Subject: [PATCH 21/36] JAVA-5734 Simplify TransactionSpan javadoc --- .../internal/observability/micrometer/TransactionSpan.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java index 38fe6123e5..6b9de83c24 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java @@ -21,9 +21,8 @@ /** * State class for transaction tracing. *

- * The transaction span is never made the current observation. Operation spans run inside the transaction are - * parented on it explicitly through {@link #getContext()}. Because no scope is held, the span may be started, - * finalized and errored from any thread. + * Unlike operation and command spans, this span never opens a scope: operation spans started inside the + * transaction are parented on it through {@link #getContext()} instead, so it can be ended from any thread. * * @since 5.7 */ From f5b6a98ba5b11c0727f1b07ab6c4912961f87e6f Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Wed, 25 Nov 2026 18:53:31 +0000 Subject: [PATCH 22/36] JAVA-5734 Use assertTrue with a clear message in the log scope tests --- .../connection/BaseClusterLogScopeTest.java | 16 ++++++++++++---- .../DefaultConnectionPoolLogScopeTest.java | 17 ++++++++++++----- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java index 25a2ad7f14..c7b69f7f93 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java @@ -44,6 +44,8 @@ import static com.mongodb.internal.logging.LogMessage.Component.SERVER_SELECTION; import static com.mongodb.internal.logging.LogMessage.Level.DEBUG; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; final class BaseClusterLogScopeTest { @@ -62,6 +64,12 @@ public synchronized void intercept(final LogMessage message) { super.intercept(message); scopeOpenAtMessage.put(message.getMessageId(), span.isScopeOpen()); } + + void assertEmittedInsideScope(final String messageId) { + Boolean scopeOpen = scopeOpenAtMessage.get(messageId); + assertNotNull(scopeOpen, messageId + " was not emitted"); + assertTrue(scopeOpen, messageId + " must be emitted inside the span scope"); + } } @Test @@ -83,10 +91,10 @@ void serverSelectionMessagesAreEmittedInsideTheOperationSpanScope() { BaseCluster.logServerSelectionFailed(operationContext, clusterId, new MongoTimeoutException("test"), selector, description); BaseCluster.logServerSelectionSucceeded(operationContext, clusterId, address, selector, description); - assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Server selection started")); - assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Waiting for suitable server to become available")); - assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Server selection failed")); - assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Server selection succeeded")); + interceptor.assertEmittedInsideScope("Server selection started"); + interceptor.assertEmittedInsideScope("Waiting for suitable server to become available"); + interceptor.assertEmittedInsideScope("Server selection failed"); + interceptor.assertEmittedInsideScope("Server selection succeeded"); assertEquals(span.openCount.get(), span.closeCount.get(), "scopes must be balanced"); } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java index e4858c54f5..5a7d037c9a 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java @@ -41,6 +41,8 @@ import static com.mongodb.internal.logging.LogMessage.Component.CONNECTION; import static com.mongodb.internal.logging.LogMessage.Level.DEBUG; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; final class DefaultConnectionPoolLogScopeTest { @@ -61,9 +63,9 @@ void checkoutMessagesAreEmittedInsideTheOperationSpanScope() { InternalConnection connection = pool.get(operationContext); connection.close(); // check in - assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Connection checkout started")); - assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Connection checked out")); - assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Connection checked in")); + interceptor.assertEmittedInsideScope("Connection checkout started"); + interceptor.assertEmittedInsideScope("Connection checked out"); + interceptor.assertEmittedInsideScope("Connection checked in"); assertEquals(span.openCount.get(), span.closeCount.get(), "scopes must be balanced"); } finally { pool.close(); @@ -90,8 +92,7 @@ void checkedInMessageUsesTheSpanOfTheMostRecentCheckout() { interceptor.scopeOpenAtMessage.clear(); pool.get(second).close(); - assertEquals(Boolean.TRUE, interceptor.scopeOpenAtMessage.get("Connection checked in"), - "checked in must use the span of the second checkout, not the first"); + interceptor.assertEmittedInsideScope("Connection checked in"); // must use the second checkout's span assertEquals(0, firstSpan.openCount.get() - firstSpan.closeCount.get()); } finally { pool.close(); @@ -112,6 +113,12 @@ public synchronized void intercept(final LogMessage message) { super.intercept(message); scopeOpenAtMessage.put(message.getMessageId(), span.isScopeOpen()); } + + void assertEmittedInsideScope(final String messageId) { + Boolean scopeOpen = scopeOpenAtMessage.get(messageId); + assertNotNull(scopeOpen, messageId + " was not emitted"); + assertTrue(scopeOpen, messageId + " must be emitted inside the span scope"); + } } static final class ScopeCountingSpan implements Span { From f4c087ed9d260b30c7da27ec439688bd1af296dd Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Wed, 25 Nov 2026 19:18:23 +0000 Subject: [PATCH 23/36] JAVA-5734 Document the purpose of BaseClusterLogScopeTest --- .../internal/connection/BaseClusterLogScopeTest.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java index c7b69f7f93..aa3f352bb1 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java @@ -47,6 +47,12 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +/** + * Verifies that the four server selection log messages are emitted while the operation span's scope is open, + * so an MDC bridge reading the current span at log time attributes them to the operation. The log helpers are + * called directly with a fake span that counts scope opens and closes; the cluster description and selector + * passed to them are only rendered into the message text, so any valid values will do. + */ final class BaseClusterLogScopeTest { /** Records, per log message id, whether the span scope was open on the thread that emitted it. */ From 8a3d726284e9aea43d23a5235ec93df7ff326a15 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Wed, 25 Nov 2026 19:23:59 +0000 Subject: [PATCH 24/36] JAVA-5734 Document the purpose of DefaultConnectionPoolLogScopeTest --- .../connection/DefaultConnectionPoolLogScopeTest.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java index 5a7d037c9a..a003bc095f 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java @@ -45,6 +45,12 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; +/** + * Verifies that the connection checkout log messages are emitted while the operation span's scope is open, so an + * MDC bridge reading the current span at log time attributes them to the operation. A real pool with a test + * connection factory is driven through checkout and check-in with a fake span that counts scope opens and closes. + * The second test covers connection reuse: "Connection checked in" must use the span of the most recent checkout. + */ final class DefaultConnectionPoolLogScopeTest { @Test From 409ce09f6152c465264eed31906b0e56c1fde481 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Wed, 25 Nov 2026 19:30:53 +0000 Subject: [PATCH 25/36] JAVA-5734 Assert the first checkout's span is not re-entered on connection reuse --- .../connection/DefaultConnectionPoolLogScopeTest.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java index a003bc095f..74516b0179 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java @@ -67,7 +67,7 @@ void checkoutMessagesAreEmittedInsideTheOperationSpanScope() { try (ScopeRecordingInterceptor interceptor = new ScopeRecordingInterceptor(applicationName, span)) { InternalConnection connection = pool.get(operationContext); - connection.close(); // check in + connection.close(); interceptor.assertEmittedInsideScope("Connection checkout started"); interceptor.assertEmittedInsideScope("Connection checked out"); @@ -96,9 +96,12 @@ void checkedInMessageUsesTheSpanOfTheMostRecentCheckout() { try (ScopeRecordingInterceptor interceptor = new ScopeRecordingInterceptor(applicationName, secondSpan)) { pool.get(first).close(); interceptor.scopeOpenAtMessage.clear(); + int firstSpanOpensBeforeSecondCheckout = firstSpan.openCount.get(); pool.get(second).close(); interceptor.assertEmittedInsideScope("Connection checked in"); // must use the second checkout's span + assertEquals(firstSpanOpensBeforeSecondCheckout, firstSpan.openCount.get(), + "the first checkout's span must not be re-entered by the second checkout"); assertEquals(0, firstSpan.openCount.get() - firstSpan.closeCount.get()); } finally { pool.close(); From 603183574c083d34368a0e125fe1a0d7c178f24e Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Wed, 25 Nov 2026 19:41:54 +0000 Subject: [PATCH 26/36] JAVA-5734 Document the goal of MicrometerSpanScopeTest --- .../observability/micrometer/MicrometerSpanScopeTest.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java index a80b3e01d0..b9f26d3b04 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java @@ -33,6 +33,14 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; +/** + * Verifies the scope contract of {@link MicrometerTracer.MicrometerSpan} against a real Micrometer registry: + * scopes nest on one thread and each close restores the previous one (both the observation and the tracing + * context); scopes opened on different threads do not interfere, so a close only affects the closing thread; + * balanced use leaves no per-thread state behind; and the error-path conveniences hold (a close with nothing + * open is a no-op, an open after {@code end()} does not throw). These properties are what let log sites in + * both the sync and the async driver re-enter a span's scope safely. + */ class MicrometerSpanScopeTest { @Test From 4c4bcd4ae22d2420b9f08bcdd6bcb0039eaaae53 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Wed, 25 Nov 2026 19:44:17 +0000 Subject: [PATCH 27/36] JAVA-5734 Document the goal of SpanRunInScopeTest --- .../observability/micrometer/SpanRunInScopeTest.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanRunInScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanRunInScopeTest.java index 74add206b8..924c8be1e6 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanRunInScopeTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanRunInScopeTest.java @@ -29,6 +29,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +/** + * Verifies the contract of {@link Span#runInScope}, the helper every log site uses to make a span current for + * the duration of a log call: a null span runs the action with no scope at all; otherwise the scope is opened + * before the action and closed after it, also when the action throws (the action's exception propagates + * unchanged); and nested calls on the same span open and close in LIFO order. A recording fake stands in for + * the span, so only the call sequence is checked here; Micrometer behaviour is covered by + * {@link MicrometerSpanScopeTest}. + */ class SpanRunInScopeTest { @Test From c72401e5e9c62e9fa2265fcbb012c952bb3bc975 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Wed, 25 Nov 2026 19:48:41 +0000 Subject: [PATCH 28/36] JAVA-5734 Remove redundant comments --- .../internal/connection/InternalStreamConnection.java | 6 +----- .../internal/observability/micrometer/MicrometerTracer.java | 1 - 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java index 8cf98d8869..fe873d23c8 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java @@ -452,9 +452,7 @@ private T sendAndReceiveInternal(final CommandMessage message, final Decoder final OperationContext operationContext) { CommandEventSender commandEventSender = new NoOpCommandEventSender(); Span tracingSpan = null; - // Single owner of the span and event sender until the message is handed off to the receive phase: - // any failure from span creation through sendCommandMessage ends the span exactly once and emits at - // most one failed event; closing a span scope that was never opened is a no-op. + try (ByteBufferBsonOutput bsonOutput = new ByteBufferBsonOutput(this)) { tracingSpan = operationContext .getTracingManager() @@ -490,7 +488,6 @@ private T sendAndReceiveInternal(final CommandMessage message, final Decoder } sendCommandMessage(message, bsonOutput, operationContext); } catch (Throwable t) { - // Emit the failed event while the span scope is still open so the log/listener see the command span. try { commandEventSender.sendFailedEvent(t); } finally { @@ -741,7 +738,6 @@ private void sendAndReceiveAsyncInternal(final CommandMessage message, final tracingSpan.setQueryText(commandDocument); } if (tracingSpan != null && isLoggingCommandNeeded) { - // The async path never holds a scope across callbacks; emit each event inside a short-lived one. commandEventSender = new TracingScopedCommandEventSender(commandEventSender, tracingSpan); } diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java index da4f4daa7d..ee506f8155 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java @@ -238,7 +238,6 @@ static String traceParent(final Observation observation) { /** * Represents a Micrometer-based span. */ - // visible for testing static class MicrometerSpan implements Span { private final Observation observation; @Nullable From cb3dafa18d5ad6df28023644ebac20d40fe6bf54 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Wed, 25 Nov 2026 19:49:41 +0000 Subject: [PATCH 29/36] JAVA-5734 Remove stray blank line --- .../mongodb/internal/connection/InternalStreamConnection.java | 1 - 1 file changed, 1 deletion(-) diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java index fe873d23c8..250ce3e650 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java @@ -452,7 +452,6 @@ private T sendAndReceiveInternal(final CommandMessage message, final Decoder final OperationContext operationContext) { CommandEventSender commandEventSender = new NoOpCommandEventSender(); Span tracingSpan = null; - try (ByteBufferBsonOutput bsonOutput = new ByteBufferBsonOutput(this)) { tracingSpan = operationContext .getTracingManager() From f104583b99ad0b8d1f9215c14f40ccceae6834ce Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Wed, 25 Nov 2026 19:56:06 +0000 Subject: [PATCH 30/36] JAVA-5734 Consolidate scope unit tests to the essentials --- .../connection/BaseClusterLogScopeTest.java | 159 ---------------- .../DefaultConnectionPoolLogScopeTest.java | 33 +--- .../InternalStreamConnectionTracingTest.java | 109 +++-------- .../micrometer/MicrometerSpanScopeTest.java | 126 +++++-------- .../micrometer/SpanRunInScopeTest.java | 125 ------------- .../micrometer/TransactionSpanTest.java | 169 ------------------ 6 files changed, 68 insertions(+), 653 deletions(-) delete mode 100644 driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java delete mode 100644 driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanRunInScopeTest.java delete mode 100644 driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanTest.java diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java deleted file mode 100644 index aa3f352bb1..0000000000 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterLogScopeTest.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.internal.connection; - -import com.mongodb.MongoTimeoutException; -import com.mongodb.MongoNamespace; -import com.mongodb.ServerAddress; -import com.mongodb.connection.ClusterDescription; -import com.mongodb.connection.ClusterId; -import com.mongodb.connection.ServerDescription; -import com.mongodb.internal.logging.LogMessage; -import com.mongodb.internal.observability.micrometer.Span; -import com.mongodb.internal.observability.micrometer.TraceContext; -import com.mongodb.internal.selector.ReadPreferenceServerSelector; -import com.mongodb.lang.Nullable; -import com.mongodb.logging.TestLoggingInterceptor; -import com.mongodb.observability.micrometer.MongodbObservationContext; -import org.bson.BsonDocument; -import org.junit.jupiter.api.Test; - -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; - -import static com.mongodb.ClusterFixture.createOperationContext; -import static com.mongodb.ReadPreference.primary; -import static com.mongodb.connection.ClusterConnectionMode.SINGLE; -import static com.mongodb.connection.ClusterType.STANDALONE; -import static com.mongodb.internal.logging.LogMessage.Component.SERVER_SELECTION; -import static com.mongodb.internal.logging.LogMessage.Level.DEBUG; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Verifies that the four server selection log messages are emitted while the operation span's scope is open, - * so an MDC bridge reading the current span at log time attributes them to the operation. The log helpers are - * called directly with a fake span that counts scope opens and closes; the cluster description and selector - * passed to them are only rendered into the message text, so any valid values will do. - */ -final class BaseClusterLogScopeTest { - - /** Records, per log message id, whether the span scope was open on the thread that emitted it. */ - private static final class ScopeRecordingInterceptor extends TestLoggingInterceptor { - private final ScopeCountingSpan span; - private final Map scopeOpenAtMessage = new ConcurrentHashMap<>(); - - ScopeRecordingInterceptor(final String applicationName, final ScopeCountingSpan span) { - super(applicationName, new LoggingFilter(Collections.singletonMap(SERVER_SELECTION, DEBUG))); - this.span = span; - } - - @Override - public synchronized void intercept(final LogMessage message) { - super.intercept(message); - scopeOpenAtMessage.put(message.getMessageId(), span.isScopeOpen()); - } - - void assertEmittedInsideScope(final String messageId) { - Boolean scopeOpen = scopeOpenAtMessage.get(messageId); - assertNotNull(scopeOpen, messageId + " was not emitted"); - assertTrue(scopeOpen, messageId + " must be emitted inside the span scope"); - } - } - - @Test - void serverSelectionMessagesAreEmittedInsideTheOperationSpanScope() { - String applicationName = "BaseClusterLogScopeTest"; - ClusterId clusterId = new ClusterId(applicationName); - ScopeCountingSpan span = new ScopeCountingSpan(); - OperationContext operationContext = createOperationContext(); - operationContext.setTracingSpan(span); - ServerAddress address = new ServerAddress(); - ClusterDescription description = new ClusterDescription(SINGLE, STANDALONE, Collections.singletonList( - ServerDescription.builder().address(address).ok(true).state(com.mongodb.connection.ServerConnectionState.CONNECTED).build())); - ReadPreferenceServerSelector selector = new ReadPreferenceServerSelector(primary()); - - try (ScopeRecordingInterceptor interceptor = new ScopeRecordingInterceptor(applicationName, span)) { - BaseCluster.logServerSelectionStarted(operationContext, clusterId, selector, description); - BaseCluster.logServerSelectionWaiting(operationContext, clusterId, - operationContext.getTimeoutContext().computeServerSelectionTimeout(), selector, description); - BaseCluster.logServerSelectionFailed(operationContext, clusterId, new MongoTimeoutException("test"), selector, description); - BaseCluster.logServerSelectionSucceeded(operationContext, clusterId, address, selector, description); - - interceptor.assertEmittedInsideScope("Server selection started"); - interceptor.assertEmittedInsideScope("Waiting for suitable server to become available"); - interceptor.assertEmittedInsideScope("Server selection failed"); - interceptor.assertEmittedInsideScope("Server selection succeeded"); - assertEquals(span.openCount.get(), span.closeCount.get(), "scopes must be balanced"); - } - } - - static final class ScopeCountingSpan implements Span { - private final AtomicInteger openCount = new AtomicInteger(); - private final AtomicInteger closeCount = new AtomicInteger(); - - boolean isScopeOpen() { - return openCount.get() > closeCount.get(); - } - - @Override - public void openScope() { - openCount.incrementAndGet(); - } - - @Override - public void closeScope() { - closeCount.incrementAndGet(); - } - - @Override - public void setQueryText(final BsonDocument commandDocument) { - } - - @Override - public void event(final String event) { - } - - @Override - public void error(final Throwable throwable) { - } - - @Override - public void end() { - } - - @Override - public TraceContext context() { - return TraceContext.EMPTY; - } - - @Override - @Nullable - public MongodbObservationContext getMongodbObservationContext() { - return null; - } - - @Override - @Nullable - public MongoNamespace getNamespace() { - return null; - } - } -} diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java index 74516b0179..5af4ed71bd 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java @@ -46,38 +46,13 @@ import static org.mockito.Mockito.mock; /** - * Verifies that the connection checkout log messages are emitted while the operation span's scope is open, so an - * MDC bridge reading the current span at log time attributes them to the operation. A real pool with a test - * connection factory is driven through checkout and check-in with a fake span that counts scope opens and closes. - * The second test covers connection reuse: "Connection checked in" must use the span of the most recent checkout. + * Verifies that the "Connection checked in" log message is emitted while the span of the most recent checkout is + * open, so an MDC bridge reading the current span at log time attributes it to the right operation. A real pool + * with a test connection factory is driven through two checkouts of the same connection, with fake spans that + * count scope opens and closes. This covers connection reuse, which the end-to-end prose tests do not. */ final class DefaultConnectionPoolLogScopeTest { - @Test - void checkoutMessagesAreEmittedInsideTheOperationSpanScope() { - String applicationName = "DefaultConnectionPoolLogScopeTest"; - ServerId serverId = new ServerId(new ClusterId(applicationName), new ServerAddress()); - ScopeCountingSpan span = new ScopeCountingSpan(); - OperationContext operationContext = createOperationContext(); - operationContext.setTracingSpan(span); - DefaultConnectionPool pool = new DefaultConnectionPool(serverId, new TestInternalConnectionFactory(), - ConnectionPoolSettings.builder().maxSize(1).build(), - SameObjectProvider.initialized(mock(SdamServerDescriptionManager.class)), OPERATION_CONTEXT_FACTORY); - pool.ready(); - - try (ScopeRecordingInterceptor interceptor = new ScopeRecordingInterceptor(applicationName, span)) { - InternalConnection connection = pool.get(operationContext); - connection.close(); - - interceptor.assertEmittedInsideScope("Connection checkout started"); - interceptor.assertEmittedInsideScope("Connection checked out"); - interceptor.assertEmittedInsideScope("Connection checked in"); - assertEquals(span.openCount.get(), span.closeCount.get(), "scopes must be balanced"); - } finally { - pool.close(); - } - } - @Test void checkedInMessageUsesTheSpanOfTheMostRecentCheckout() { String applicationName = "DefaultConnectionPoolLogScopeTest2"; diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java index 918be15b87..3709d1dba0 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java @@ -43,6 +43,8 @@ import org.bson.codecs.BsonDocumentCodec; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import java.io.ByteArrayOutputStream; import java.util.List; @@ -285,42 +287,27 @@ public void commandFailed(final CommandFailedEvent event) { } } - @Test - @DisplayName("Sync: started and succeeded command events fire while the command span scope is open") - void syncCommandEventsFireInsideSpanScope() { + @ParameterizedTest(name = "async={0}") + @ValueSource(booleans = {false, true}) + @DisplayName("Started and succeeded command events fire while the command span scope is open") + void commandEventsFireInsideSpanScope(final boolean async) throws Exception { AtomicInteger readCallCount = new AtomicInteger(); CapturingTestStream stream = new CapturingTestStream() { - @Override - public ByteBuf read(final int numBytes, final OperationContext operationContext) { + private ByteBuf nextResponseChunk() { return readCallCount.incrementAndGet() == 1 ? createValidResponseHeader(getCommandMessageId()) : createResponseBody(new BsonDocument("ok", new BsonInt32(1))); } - }; - RecordingSpan span = new RecordingSpan(); - ScopeObservingListener listener = new ScopeObservingListener(span); - InternalStreamConnection connection = createOpenConnection(stream, listener); - CommandMessage commandMessage = createPingCommand(); - stream.setCommandMessageId(commandMessage.getId()); - connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), createTracedOperationContext(span)); - assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("started"), "started event must see the span scope"); - assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("succeeded"), "succeeded event must see the span scope"); - assertEquals(span.openScopeCount.get(), span.closeScopeCount.get(), "scopes must be balanced"); - assertEquals(1, span.endCount.get()); - connection.close(); - } - @Test - @DisplayName("Async: started and succeeded command events fire while the command span scope is open") - void asyncCommandEventsFireInsideSpanScope() { - AtomicInteger readAsyncCallCount = new AtomicInteger(); - CapturingTestStream stream = new CapturingTestStream() { + @Override + public ByteBuf read(final int numBytes, final OperationContext operationContext) { + return nextResponseChunk(); + } + @Override public void readAsync(final int numBytes, final OperationContext operationContext, final AsyncCompletionHandler handler) { - handler.completed(readAsyncCallCount.incrementAndGet() == 1 - ? createValidResponseHeader(getCommandMessageId()) - : createResponseBody(new BsonDocument("ok", new BsonInt32(1)))); + handler.completed(nextResponseChunk()); } }; RecordingSpan span = new RecordingSpan(); @@ -328,9 +315,13 @@ public void readAsync(final int numBytes, final OperationContext operationContex InternalStreamConnection connection = createOpenConnection(stream, listener); CommandMessage commandMessage = createPingCommand(); stream.setCommandMessageId(commandMessage.getId()); - FutureResultCallback callback = new FutureResultCallback<>(); - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), createTracedOperationContext(span), callback); - callback.get(5, TimeUnit.SECONDS); + if (async) { + FutureResultCallback callback = new FutureResultCallback<>(); + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), createTracedOperationContext(span), callback); + callback.get(5, TimeUnit.SECONDS); + } else { + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), createTracedOperationContext(span)); + } assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("started"), "started event must see the span scope"); assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("succeeded"), "succeeded event must see the span scope"); assertEquals(span.openScopeCount.get(), span.closeScopeCount.get(), "scopes must be balanced"); @@ -338,66 +329,6 @@ public void readAsync(final int numBytes, final OperationContext operationContex connection.close(); } - @Test - @DisplayName("Sync: failed command event fires inside the span scope when the write fails") - void syncFailedEventFiresInsideSpanScope() { - CapturingTestStream stream = new CapturingTestStream() { - @Override - public void write(final List buffers, final OperationContext operationContext) { - throw new RuntimeException("simulated write failure"); - } - }; - RecordingSpan span = new RecordingSpan(); - ScopeObservingListener listener = new ScopeObservingListener(span); - InternalStreamConnection connection = createOpenConnection(stream, listener); - assertThrows(MongoInternalException.class, - () -> connection.sendAndReceive(createPingCommand(), new BsonDocumentCodec(), createTracedOperationContext(span))); - assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("failed"), "failed event must see the span scope"); - assertEquals(span.openScopeCount.get(), span.closeScopeCount.get(), "scopes must be balanced"); - assertEquals(1, span.endCount.get()); - connection.close(); - } - - @Test - @DisplayName("Async: failed command event fires inside the span scope when the write fails") - void asyncFailedEventFiresInsideSpanScope() { - CapturingTestStream stream = new CapturingTestStream() { - @Override - public void writeAsync(final List buffers, final OperationContext operationContext, - final AsyncCompletionHandler handler) { - handler.failed(new RuntimeException("simulated async write failure")); - } - }; - RecordingSpan span = new RecordingSpan(); - ScopeObservingListener listener = new ScopeObservingListener(span); - InternalStreamConnection connection = createOpenConnection(stream, listener); - FutureResultCallback callback = new FutureResultCallback<>(); - connection.sendAndReceiveAsync(createPingCommand(), new BsonDocumentCodec(), createTracedOperationContext(span), callback); - assertThrows(RuntimeException.class, () -> callback.get(5, TimeUnit.SECONDS)); - assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("failed"), "failed event must see the span scope"); - assertEquals(span.openScopeCount.get(), span.closeScopeCount.get(), "scopes must be balanced"); - assertEquals(1, span.endCount.get()); - connection.close(); - } - - @Test - @DisplayName("Async: one-way (w:0) succeeded event fires inside the span scope") - void asyncOneWaySucceededEventFiresInsideSpanScope() { - CapturingTestStream stream = new CapturingTestStream() { - }; - RecordingSpan span = new RecordingSpan(); - ScopeObservingListener listener = new ScopeObservingListener(span); - InternalStreamConnection connection = createOpenConnection(stream, listener); - FutureResultCallback callback = new FutureResultCallback<>(); - connection.sendAndReceiveAsync(createUnacknowledgedInsertCommand(), new BsonDocumentCodec(), - createTracedOperationContext(span), callback); - assertNull(callback.get(5, TimeUnit.SECONDS)); - assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("succeeded"), "one-way succeeded event must see the span scope"); - assertEquals(span.openScopeCount.get(), span.closeScopeCount.get(), "scopes must be balanced"); - assertEquals(1, span.endCount.get()); - connection.close(); - } - private static CommandMessage createUnacknowledgedInsertCommand() { BsonDocument insert = new BsonDocument("insert", new BsonString("coll")) .append("documents", new BsonArray(singletonList(new BsonDocument("_id", new BsonInt32(1))))) diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java index b9f26d3b04..4a29540da1 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java @@ -26,76 +26,51 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Verifies the scope contract of {@link MicrometerTracer.MicrometerSpan} against a real Micrometer registry: - * scopes nest on one thread and each close restores the previous one (both the observation and the tracing - * context); scopes opened on different threads do not interfere, so a close only affects the closing thread; - * balanced use leaves no per-thread state behind; and the error-path conveniences hold (a close with nothing - * open is a no-op, an open after {@code end()} does not throw). These properties are what let log sites in - * both the sync and the async driver re-enter a span's scope safely. + * nested scopes on one thread restore the previous observation and tracing context, and balanced use leaves no + * per-thread state behind; a close only affects the closing thread; the error-path conveniences hold (a close + * with nothing open is a no-op, an open after {@code end()} does not throw); and {@link Span#runInScope} closes + * the scope even when the action throws. These properties are what let log sites in both the sync and the async + * driver re-enter a span's scope safely. */ class MicrometerSpanScopeTest { @Test - void nestedOpenAndCloseRestoreTheOuterScope() { - TestObservationRegistry registry = TestObservationRegistry.create(); + void nestedScopesRestoreTheOuterScope() { + ObservationRegistry registry = ObservationRegistry.create(); + SimpleTracer tracer = new SimpleTracer(); + registry.observationConfig().observationHandler(new DefaultTracingObservationHandler(tracer)); Observation observation = Observation.start("op", registry); - Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); + TracingObservationHandler.TracingContext tracingContext = + observation.getContextView().get(TracingObservationHandler.TracingContext.class); + io.micrometer.tracing.Span observationSpan = tracingContext.getSpan(); + MicrometerTracer.MicrometerSpan span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); + assertTrue(span.isThreadLocalEmpty(), "no thread-local entry may exist before the first open"); span.openScope(); // outer, e.g. MongoClusterImpl assertSame(observation, registry.getCurrentObservation()); + assertFalse(span.isThreadLocalEmpty(), "an open scope must be tracked"); Observation.Scope outerScope = registry.getCurrentObservationScope(); span.openScope(); // inner, e.g. DefaultConnectionPool at log time assertSame(observation, registry.getCurrentObservation()); span.closeScope(); // inner close - assertSame(observation, registry.getCurrentObservation(), "outer scope must still be current"); + assertSame(observation, registry.getCurrentObservation(), "the observation must still be current after the inner close"); assertSame(outerScope, registry.getCurrentObservationScope(), "the outer scope itself must be current"); + assertSame(observationSpan, tracer.currentSpan(), "the observation's span must still be current after the inner close"); span.closeScope(); // outer close - assertNull(registry.getCurrentObservation(), "no scope may remain after balanced closes"); - observation.stop(); - } - - @Test - void openScopeAfterEndDoesNotThrow() { - ObservationRegistry registry = TestObservationRegistry.create(); - Observation observation = Observation.start("op", registry); - Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); - span.end(); - assertDoesNotThrow(span::openScope); - assertDoesNotThrow(span::closeScope); - } - - @Test - void scopesOpenedOnDifferentThreadsAreIndependent() throws Exception { - TestObservationRegistry registry = TestObservationRegistry.create(); - Observation observation = Observation.start("op", registry); - Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); - - span.openScope(); // thread A (this thread) opens the scope - assertSame(observation, registry.getCurrentObservation()); - - ExecutorService threadB = Executors.newSingleThreadExecutor(); - try { - threadB.submit(() -> { - span.openScope(); // thread B opens its own scope on the same span - span.closeScope(); // and closes it again - assertNull(registry.getCurrentObservation(), "thread B leaves no scope open on its thread"); - }).get(); // surface thread B's failures on this thread - } finally { - threadB.shutdown(); - } - - assertSame(observation, registry.getCurrentObservation(), - "thread A's scope must survive thread B's open/close"); - span.closeScope(); // thread A closes its scope - assertNull(registry.getCurrentObservation(), "no scope may remain after balanced closes"); + assertNull(registry.getCurrentObservation(), "no observation may remain current after balanced closes"); + assertNull(tracer.currentSpan(), "no span may remain current after balanced closes"); + assertTrue(span.isThreadLocalEmpty(), "a balanced open/close must clear the thread-local"); observation.stop(); } @@ -134,52 +109,39 @@ void aThreadsCloseDoesNotCloseAnotherThreadsScope() throws Exception { } @Test - void balancedOpenAndCloseLeaveNoThreadLocalEntry() { + void closeWithoutOpenAndOpenAfterEndAreSafe() { ObservationRegistry registry = TestObservationRegistry.create(); Observation observation = Observation.start("op", registry); MicrometerTracer.MicrometerSpan span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); - assertTrue(span.isThreadLocalEmpty(), "no thread-local entry may exist before the first open"); - span.closeScope(); + span.closeScope(); // nothing open: must be a no-op + assertNull(registry.getCurrentObservation(), "an unmatched close must not change the current observation"); assertTrue(span.isThreadLocalEmpty(), "an unmatched close must not create a thread-local entry"); - span.openScope(); - assertFalse(span.isThreadLocalEmpty(), "an open scope must be tracked"); - span.closeScope(); - assertTrue(span.isThreadLocalEmpty(), "a balanced open/close must clear the thread-local"); - observation.stop(); - } - @Test - void nestedScopesRestoreTheOuterTracingContext() { - ObservationRegistry registry = ObservationRegistry.create(); - SimpleTracer tracer = new SimpleTracer(); - registry.observationConfig().observationHandler(new DefaultTracingObservationHandler(tracer)); - Observation observation = Observation.start("op", registry); - TracingObservationHandler.TracingContext tracingContext = - observation.getContextView().get(TracingObservationHandler.TracingContext.class); - io.micrometer.tracing.Span observationSpan = tracingContext.getSpan(); - Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); - - span.openScope(); - span.openScope(); - span.closeScope(); - assertSame(observationSpan, tracer.currentSpan(), "the observation's span must still be current after the inner close"); - assertSame(observation, registry.getCurrentObservation(), "the observation itself must still be current"); - span.closeScope(); - assertNull(tracer.currentSpan(), "no span may remain current after balanced closes"); - assertNull(registry.getCurrentObservation(), "no observation may remain current after balanced closes"); - observation.stop(); + span.end(); + assertDoesNotThrow(span::openScope); + assertDoesNotThrow(span::closeScope); + assertTrue(span.isThreadLocalEmpty(), "a balanced open/close after end must clear the thread-local"); } @Test - void extraCloseIsNoOp() { + void runInScopeClosesTheScopeWhenTheActionThrows() { ObservationRegistry registry = TestObservationRegistry.create(); Observation observation = Observation.start("op", registry); - Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); - span.closeScope(); - span.openScope(); - span.closeScope(); - assertDoesNotThrow(span::closeScope); + MicrometerTracer.MicrometerSpan span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); + RuntimeException failure = new RuntimeException("appender failed"); + + RuntimeException thrown = assertThrows(RuntimeException.class, () -> Span.runInScope(span, () -> { + throw failure; + })); + + assertSame(failure, thrown, "the action's exception must propagate unchanged"); + assertNull(registry.getCurrentObservation(), "the scope must be closed when the action throws"); + assertTrue(span.isThreadLocalEmpty(), "the failed action must not leave a thread-local entry"); + + AtomicBoolean ran = new AtomicBoolean(); + Span.runInScope(null, () -> ran.set(true)); + assertTrue(ran.get(), "a null span must run the action without opening a scope"); observation.stop(); } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanRunInScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanRunInScopeTest.java deleted file mode 100644 index 924c8be1e6..0000000000 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/SpanRunInScopeTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.internal.observability.micrometer; - -import com.mongodb.MongoNamespace; -import com.mongodb.lang.Nullable; -import com.mongodb.observability.micrometer.MongodbObservationContext; -import org.bson.BsonDocument; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; - -import static java.util.Arrays.asList; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -/** - * Verifies the contract of {@link Span#runInScope}, the helper every log site uses to make a span current for - * the duration of a log call: a null span runs the action with no scope at all; otherwise the scope is opened - * before the action and closed after it, also when the action throws (the action's exception propagates - * unchanged); and nested calls on the same span open and close in LIFO order. A recording fake stands in for - * the span, so only the call sequence is checked here; Micrometer behaviour is covered by - * {@link MicrometerSpanScopeTest}. - */ -class SpanRunInScopeTest { - - @Test - void runsActionDirectlyWhenSpanIsNull() { - List calls = new ArrayList<>(); - Span.runInScope(null, () -> calls.add("action")); - assertEquals(asList("action"), calls); - } - - @Test - void opensScopeBeforeActionAndClosesAfter() { - List calls = new ArrayList<>(); - Span.runInScope(new RecordingSpan(calls), () -> calls.add("action")); - assertEquals(asList("open", "action", "close"), calls); - } - - @Test - void closesScopeWhenActionThrows() { - List calls = new ArrayList<>(); - RuntimeException failure = new RuntimeException("appender failed"); - RuntimeException thrown = assertThrows(RuntimeException.class, () -> Span.runInScope(new RecordingSpan(calls), () -> { - throw failure; - })); - assertEquals(failure, thrown); - assertEquals(asList("open", "close"), calls); - } - - @Test - void nestsScopes() { - List calls = new ArrayList<>(); - RecordingSpan span = new RecordingSpan(calls); - Span.runInScope(span, () -> Span.runInScope(span, () -> calls.add("action"))); - assertEquals(asList("open", "open", "action", "close", "close"), calls); - } - - static final class RecordingSpan implements Span { - private final List calls; - - RecordingSpan(final List calls) { - this.calls = calls; - } - - @Override - public void openScope() { - calls.add("open"); - } - - @Override - public void closeScope() { - calls.add("close"); - } - - @Override - public void setQueryText(final BsonDocument commandDocument) { - } - - @Override - public void event(final String event) { - } - - @Override - public void error(final Throwable throwable) { - } - - @Override - public void end() { - } - - @Override - public TraceContext context() { - return TraceContext.EMPTY; - } - - @Override - @Nullable - public MongodbObservationContext getMongodbObservationContext() { - return null; - } - - @Override - @Nullable - public MongoNamespace getNamespace() { - return null; - } - } -} diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanTest.java deleted file mode 100644 index d980c7074c..0000000000 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/TransactionSpanTest.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.internal.observability.micrometer; - -import com.mongodb.MongoNamespace; -import com.mongodb.ReadConcern; -import com.mongodb.internal.IgnorableRequestContext; -import com.mongodb.internal.TimeoutContext; -import com.mongodb.internal.TimeoutSettings; -import com.mongodb.internal.connection.OperationContext; -import com.mongodb.internal.connection.ReadConcernAwareNoOpSessionContext; -import com.mongodb.observability.ObservabilitySettings; -import com.mongodb.observability.micrometer.MongodbObservation; -import io.micrometer.observation.Observation; -import io.micrometer.observation.ObservationHandler; -import io.micrometer.observation.ObservationRegistry; -import io.micrometer.observation.ObservationView; -import io.micrometer.observation.tck.TestObservationRegistry; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; - -/** - * The transaction span is never made the current observation, so it can be started, finalized and errored on any - * thread without leaving a scope behind; operation spans are parented on it explicitly through - * {@link TransactionSpan#getContext()}. - */ -class TransactionSpanTest { - - @Test - void creatingATransactionSpanDoesNotMakeItCurrent() { - TestObservationRegistry registry = TestObservationRegistry.create(); - AtomicInteger stopCount = countStops(registry); - TransactionSpan transactionSpan = new TransactionSpan(tracingManager(registry)); - - assertNull(registry.getCurrentObservation(), "creating the transaction span must not make it current"); - - transactionSpan.finalizeTransactionSpan("COMMITTED"); - assertEquals(1, stopCount.get(), "finalizing must end the transaction span exactly once"); - assertNull(registry.getCurrentObservation(), "finalizing must leave no observation current"); - } - - @Test - void finalizeOnAnotherThreadEndsTheSpanAndLeavesNoScopeOnEitherThread() throws Exception { - TestObservationRegistry registry = TestObservationRegistry.create(); - AtomicInteger stopCount = countStops(registry); - TransactionSpan transactionSpan = new TransactionSpan(tracingManager(registry)); // thread A (this thread) - - ExecutorService threadB = Executors.newSingleThreadExecutor(); - try { - threadB.submit(() -> { - transactionSpan.finalizeTransactionSpan("COMMITTED"); - assertNull(registry.getCurrentObservation(), "finalizing on thread B must leave no observation current there"); - }).get(); // surface thread B's failures on this thread - } finally { - threadB.shutdown(); - } - - assertEquals(1, stopCount.get(), "finalizing on thread B must end the transaction span exactly once"); - assertNull(registry.getCurrentObservation(), "thread A must have no observation current"); - } - - @Test - void handleTransactionSpanErrorOnAnotherThreadBehavesTheSame() throws Exception { - TestObservationRegistry registry = TestObservationRegistry.create(); - AtomicInteger stopCount = countStops(registry); - TransactionSpan transactionSpan = new TransactionSpan(tracingManager(registry)); // thread A (this thread) - - ExecutorService threadB = Executors.newSingleThreadExecutor(); - try { - threadB.submit(() -> { - // non-convenient transaction: the error is recorded and the span is ended - transactionSpan.handleTransactionSpanError(new RuntimeException("boom")); - assertNull(registry.getCurrentObservation(), "handling the error on thread B must leave no observation current there"); - }).get(); // surface thread B's failures on this thread - } finally { - threadB.shutdown(); - } - - assertEquals(1, stopCount.get(), "handling the error on thread B must end the transaction span exactly once"); - assertNull(registry.getCurrentObservation(), "thread A must have no observation current"); - } - - @Test - void operationSpanCreatedInsideTransactionIsParentedOnTheTransactionSpan() { - TestObservationRegistry registry = TestObservationRegistry.create(); - List startedContexts = new CopyOnWriteArrayList<>(); - registry.observationConfig().observationHandler(new ObservationHandler() { - @Override - public void onStart(final Observation.Context context) { - startedContexts.add(context); - } - - @Override - public boolean supportsContext(final Observation.Context context) { - return true; - } - }); - TracingManager tracingManager = tracingManager(registry); - TransactionSpan transactionSpan = new TransactionSpan(tracingManager); - OperationContext operationContext = new OperationContext(IgnorableRequestContext.INSTANCE, - new ReadConcernAwareNoOpSessionContext(ReadConcern.DEFAULT), new TimeoutContext(TimeoutSettings.DEFAULT), null); - - Span operationSpan = tracingManager.createOperationSpan(transactionSpan, operationContext, "insert", - new MongoNamespace("db.coll")); - assertNotNull(operationSpan); - - assertEquals(2, startedContexts.size(), "the transaction and operation observations must have started"); - Observation.Context transactionContext = startedContexts.get(0); - Observation.Context operationContextView = startedContexts.get(1); - assertEquals(MongodbObservation.MONGODB_TRANSACTION.getName(), transactionContext.getName()); - assertEquals(MongodbObservation.MONGODB_OPERATION.getName(), operationContextView.getName()); - ObservationView parent = operationContextView.getParentObservation(); - assertNotNull(parent, "the operation observation must have a parent"); - assertSame(transactionContext, parent.getContextView(), "the operation observation must be parented on the transaction"); - - operationSpan.end(); - transactionSpan.finalizeTransactionSpan("COMMITTED"); - assertNull(registry.getCurrentObservation(), "no observation must remain current"); - } - - private static TracingManager tracingManager(final ObservationRegistry registry) { - return new TracingManager(ObservabilitySettings.micrometerBuilder() - .observationRegistry(registry) - .build()); - } - - /** - * Registers a handler that counts {@code onStop} calls so the tests can assert that the span actually ended. - */ - private static AtomicInteger countStops(final ObservationRegistry registry) { - AtomicInteger stopCount = new AtomicInteger(); - registry.observationConfig().observationHandler(new ObservationHandler() { - @Override - public void onStop(final Observation.Context context) { - stopCount.incrementAndGet(); - } - - @Override - public boolean supportsContext(final Observation.Context context) { - return true; - } - }); - return stopCount; - } -} From 77615b24c5ac8ae76f1a8dc9790cac12912e976b Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Wed, 25 Nov 2026 23:43:50 +0000 Subject: [PATCH 31/36] JAVA-5734 Drop volatile from PooledConnection.operationSpan to match operationId --- .../com/mongodb/internal/connection/DefaultConnectionPool.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java index 6994d69dc9..3e40e3ae63 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java +++ b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java @@ -622,7 +622,7 @@ private class PooledConnection implements InternalConnection { private Connection.PinningMode pinningMode; private long operationId; @Nullable - private volatile Span operationSpan; + private Span operationSpan; PooledConnection(final UsageTrackingInternalConnection wrapped) { this.wrapped = notNull("wrapped", wrapped); From 14975e4fd4d054686442378164fadc971c5744bd Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 26 Nov 2026 00:03:30 +0000 Subject: [PATCH 32/36] JAVA-5734 Return a closeable handle from Span.openScope and drop the per-thread scope stack Span.openScope() returned void, so MicrometerSpan had to remember which Micrometer scope to close and kept a ThreadLocal> for it. openScope() now returns a SpanScope handle (AutoCloseable, no checked exception) that the caller closes on the same thread. The span holds no scope state, and open/close pairing is enforced by the compiler via try-with-resources or an explicit handle. closeScope() is removed. Behaviour is unchanged: the same scopes open and close at the same points, and span start/end timing is untouched. SpanScope.NO_OP keeps the old "close before open is a no-op" behaviour on the sync send failure path. Call sites converted: - InternalStreamConnection sync path (sendAndReceiveInternal and receiveCommandMessageResponse, which now takes the scope) - TracingScopedCommandEventSender (four event methods) - MongoClusterImpl read and write execute - Span.runInScope (used by BaseCluster and DefaultConnectionPool, which need no change) --- .../connection/InternalStreamConnection.java | 16 ++-- .../TracingScopedCommandEventSender.java | 21 ++--- .../micrometer/MicrometerTracer.java | 36 +-------- .../observability/micrometer/Span.java | 33 +++----- .../observability/micrometer/SpanScope.java | 32 ++++++++ .../DefaultConnectionPoolLogScopeTest.java | 9 +-- .../InternalStreamConnectionTracingTest.java | 15 ++-- .../micrometer/MicrometerSpanScopeTest.java | 78 ++++--------------- .../micrometer/MicrometerTraceParentTest.java | 9 +-- .../MicrometerTracerRecordingTest.java | 7 +- .../client/internal/MongoClusterImpl.java | 11 ++- 11 files changed, 96 insertions(+), 171 deletions(-) create mode 100644 driver-core/src/main/com/mongodb/internal/observability/micrometer/SpanScope.java diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java index 250ce3e650..16bb5cccd8 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java @@ -51,6 +51,7 @@ import com.mongodb.internal.diagnostics.logging.Loggers; import com.mongodb.internal.logging.StructuredLogger; import com.mongodb.internal.observability.micrometer.Span; +import com.mongodb.internal.observability.micrometer.SpanScope; import com.mongodb.internal.session.SessionContext; import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; @@ -452,6 +453,7 @@ private T sendAndReceiveInternal(final CommandMessage message, final Decoder final OperationContext operationContext) { CommandEventSender commandEventSender = new NoOpCommandEventSender(); Span tracingSpan = null; + SpanScope tracingScope = SpanScope.NO_OP; try (ByteBufferBsonOutput bsonOutput = new ByteBufferBsonOutput(this)) { tracingSpan = operationContext .getTracingManager() @@ -476,7 +478,7 @@ private T sendAndReceiveInternal(final CommandMessage message, final Decoder } // Open the scope before the started event so command listeners and logs observe the command span. if (tracingSpan != null) { - tracingSpan.openScope(); + tracingScope = tracingSpan.openScope(); } if (isLoggingCommandNeeded) { commandEventSender = new LoggingCommandEventSender( @@ -492,7 +494,7 @@ private T sendAndReceiveInternal(final CommandMessage message, final Decoder } finally { if (tracingSpan != null) { tracingSpan.error(t); - tracingSpan.closeScope(); + tracingScope.close(); tracingSpan.end(); } } @@ -500,11 +502,11 @@ private T sendAndReceiveInternal(final CommandMessage message, final Decoder } if (message.isResponseExpected()) { - return receiveCommandMessageResponse(decoder, commandEventSender, operationContext, tracingSpan); + return receiveCommandMessageResponse(decoder, commandEventSender, operationContext, tracingSpan, tracingScope); } else { commandEventSender.sendSucceededEventForOneWayCommand(); if (tracingSpan != null) { - tracingSpan.closeScope(); + tracingScope.close(); tracingSpan.end(); } return null; @@ -526,7 +528,7 @@ public void send(final CommandMessage message, final Decoder decoder, fin @Override public T receive(final Decoder decoder, final OperationContext operationContext) { isTrue("Response is expected", hasMoreToCome); - return receiveCommandMessageResponse(decoder, new NoOpCommandEventSender(), operationContext, null); + return receiveCommandMessageResponse(decoder, new NoOpCommandEventSender(), operationContext, null, SpanScope.NO_OP); } @Override @@ -572,13 +574,13 @@ private void trySendMessage(final CommandMessage message, final ByteBufferBsonOu } private T receiveCommandMessageResponse(final Decoder decoder, final CommandEventSender commandEventSender, - final OperationContext operationContext, @Nullable final Span tracingSpan) { + final OperationContext operationContext, @Nullable final Span tracingSpan, final SpanScope tracingScope) { try { ResponseBuffers responseBuffers = receiveCommandResponseBuffers(commandEventSender, operationContext, tracingSpan); return processCommandResponse(decoder, responseBuffers, commandEventSender, operationContext, tracingSpan); } finally { if (tracingSpan != null) { - tracingSpan.closeScope(); + tracingScope.close(); tracingSpan.end(); } } diff --git a/driver-core/src/main/com/mongodb/internal/connection/TracingScopedCommandEventSender.java b/driver-core/src/main/com/mongodb/internal/connection/TracingScopedCommandEventSender.java index 6cbc3f0b7f..36e87fc81b 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/TracingScopedCommandEventSender.java +++ b/driver-core/src/main/com/mongodb/internal/connection/TracingScopedCommandEventSender.java @@ -17,6 +17,7 @@ package com.mongodb.internal.connection; import com.mongodb.internal.observability.micrometer.Span; +import com.mongodb.internal.observability.micrometer.SpanScope; /** * A {@link CommandEventSender} for the asynchronous path that opens the command span's scope around each event, @@ -35,41 +36,29 @@ final class TracingScopedCommandEventSender implements CommandEventSender { @Override public void sendStartedEvent() { - span.openScope(); - try { + try (SpanScope ignored = span.openScope()) { delegate.sendStartedEvent(); - } finally { - span.closeScope(); } } @Override public void sendFailedEvent(final Throwable t) { - span.openScope(); - try { + try (SpanScope ignored = span.openScope()) { delegate.sendFailedEvent(t); - } finally { - span.closeScope(); } } @Override public void sendSucceededEvent(final ResponseBuffers responseBuffers) { - span.openScope(); - try { + try (SpanScope ignored = span.openScope()) { delegate.sendSucceededEvent(responseBuffers); - } finally { - span.closeScope(); } } @Override public void sendSucceededEventForOneWayCommand() { - span.openScope(); - try { + try (SpanScope ignored = span.openScope()) { delegate.sendSucceededEventForOneWayCommand(); - } finally { - span.closeScope(); } } } diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java index ee506f8155..c6d04286db 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java @@ -32,8 +32,6 @@ import org.bson.json.JsonWriterSettings; import java.io.StringWriter; -import java.util.ArrayDeque; -import java.util.Deque; import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE; import static com.mongodb.internal.observability.micrometer.TracingManager.ENV_OBSERVABILITY_QUERY_TEXT_MAX_LENGTH; @@ -243,11 +241,6 @@ static class MicrometerSpan implements Span { @Nullable private final MongoNamespace namespace; private final int queryTextLength; - // Open scopes of this span, per thread. A Micrometer scope is thread-local state, and in the async driver - // the same span is made current from several threads (e.g. the operation span from the caller thread, a - // Netty thread and the cluster thread as each one logs). Each thread must close only the scopes it opened, - // and a thread may hold more than one at a time when a log site re-enters a scope that is already open. - private final ThreadLocal> scopes = new ThreadLocal<>(); /** * Constructs a new {@link MicrometerSpan} instance with an associated Observation and MongoDB namespace. @@ -263,32 +256,9 @@ static class MicrometerSpan implements Span { } @Override - public void openScope() { - Deque deque = scopes.get(); - if (deque == null) { - deque = new ArrayDeque<>(); - scopes.set(deque); - } - deque.push(observation.openScope()); - } - - @Override - public void closeScope() { - Deque deque = scopes.get(); - if (deque == null) { - return; - } - Observation.Scope scope = deque.poll(); - if (scope != null) { - scope.close(); - } - if (deque.isEmpty()) { - scopes.remove(); - } - } - - boolean isThreadLocalEmpty() { - return scopes.get() == null; + public SpanScope openScope() { + Observation.Scope scope = observation.openScope(); + return scope::close; } @Override diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java index 0e81f6bfb6..481b13cc1b 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java @@ -47,11 +47,8 @@ public interface Span { */ Span EMPTY = new Span() { @Override - public void openScope() { - } - - @Override - public void closeScope() { + public SpanScope openScope() { + return SpanScope.NO_OP; } @Override @@ -89,22 +86,13 @@ public MongodbObservationContext getMongodbObservationContext() { }; /** - * Opens a scope for this span, making it the current observation on the calling thread. - * Every successful {@code openScope()} must be matched by a {@link #closeScope()} on the same thread; - * scopes nest per thread, so a thread may open the scope again before closing it. - * Calling {@code openScope()} after {@link #end()} does not throw. - */ - void openScope(); - - /** - * Closes the most recently opened scope for this span on the calling thread, restoring the - * previous observation. Each {@code closeScope()} must be called on the same thread as its - * matching {@code openScope()}; scopes nest per thread, and an equal number of - * {@code openScope()} and {@code closeScope()} calls on a thread leaves no scope open on it. - * Calling this with no open scope on the calling thread is a no-op — error-handling paths may - * therefore call it unconditionally. + * Makes this span the current span on the calling thread until the returned scope is closed. Close it on the + * same thread, normally with try-with-resources. Scopes nest: closing the inner one restores the outer. + * Opening a scope after {@link #end()} is allowed. + * + * @return the scope, which must be closed on the calling thread */ - void closeScope(); + SpanScope openScope(); /** * Sets the query text on the observation context from the given command document. @@ -170,11 +158,8 @@ static void runInScope(@Nullable final Span span, final Runnable action) { action.run(); return; } - span.openScope(); - try { + try (SpanScope ignored = span.openScope()) { action.run(); - } finally { - span.closeScope(); } } } diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/SpanScope.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/SpanScope.java new file mode 100644 index 0000000000..662b02383a --- /dev/null +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/SpanScope.java @@ -0,0 +1,32 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.observability.micrometer; + +/** + * A handle to a scope opened by {@link Span#openScope()}; closing it restores the previously current span on the + * thread that opened it. + */ +public interface SpanScope extends AutoCloseable { + /** + * A scope that does nothing when closed. + */ + SpanScope NO_OP = () -> { + }; + + @Override + void close(); +} diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java index 5af4ed71bd..d3b9618034 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java @@ -24,6 +24,7 @@ import com.mongodb.internal.inject.SameObjectProvider; import com.mongodb.internal.logging.LogMessage; import com.mongodb.internal.observability.micrometer.Span; +import com.mongodb.internal.observability.micrometer.SpanScope; import com.mongodb.internal.observability.micrometer.TraceContext; import com.mongodb.lang.Nullable; import com.mongodb.logging.TestLoggingInterceptor; @@ -114,13 +115,9 @@ boolean isScopeOpen() { } @Override - public void openScope() { + public SpanScope openScope() { openCount.incrementAndGet(); - } - - @Override - public void closeScope() { - closeCount.incrementAndGet(); + return closeCount::incrementAndGet; } @Override diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java index 3709d1dba0..3d460a33f4 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java @@ -29,6 +29,7 @@ import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.connection.MessageSequences.EmptyMessageSequences; import com.mongodb.internal.observability.micrometer.Span; +import com.mongodb.internal.observability.micrometer.SpanScope; import com.mongodb.internal.observability.micrometer.TraceContext; import com.mongodb.internal.observability.micrometer.TracingManager; import com.mongodb.internal.thread.AsyncClientExecutor; @@ -121,7 +122,7 @@ public ByteBuf read(final int numBytes, final OperationContext operationContext) /** * Verifies exactly-once span termination when the sync send fails: the widened {@code catch (Throwable)} - * must fire {@code error()}/{@code closeScope()}/{@code end()} once each, with no double-firing from the + * must fire {@code error()}/scope close/{@code end()} once each, with no double-firing from the * receive path (which is never reached). */ @Test @@ -268,7 +269,7 @@ private static final class ScopeObservingListener implements CommandListener { } private void record(final String event) { - scopeOpenAtEvent.put(event, span.openScopeCount.get() > span.closeScopeCount.get()); + scopeOpenAtEvent.put(event, span.openScopeCount.get() > span.scopeCloseCount.get()); } @Override @@ -324,7 +325,7 @@ public void readAsync(final int numBytes, final OperationContext operationContex } assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("started"), "started event must see the span scope"); assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("succeeded"), "succeeded event must see the span scope"); - assertEquals(span.openScopeCount.get(), span.closeScopeCount.get(), "scopes must be balanced"); + assertEquals(span.openScopeCount.get(), span.scopeCloseCount.get(), "scopes must be balanced"); assertEquals(1, span.endCount.get()); connection.close(); } @@ -417,13 +418,9 @@ private static final class RecordingSpan implements Span { private final AtomicInteger endCount = new AtomicInteger(); @Override - public void openScope() { + public SpanScope openScope() { openScopeCount.incrementAndGet(); - } - - @Override - public void closeScope() { - closeScopeCount.incrementAndGet(); + return closeScopeCount::incrementAndGet; } @Override diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java index 4a29540da1..c7e7d6d87a 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java @@ -24,12 +24,9 @@ import io.micrometer.tracing.test.simple.SimpleTracer; import org.junit.jupiter.api.Test; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -37,11 +34,9 @@ /** * Verifies the scope contract of {@link MicrometerTracer.MicrometerSpan} against a real Micrometer registry: - * nested scopes on one thread restore the previous observation and tracing context, and balanced use leaves no - * per-thread state behind; a close only affects the closing thread; the error-path conveniences hold (a close - * with nothing open is a no-op, an open after {@code end()} does not throw); and {@link Span#runInScope} closes - * the scope even when the action throws. These properties are what let log sites in both the sync and the async - * driver re-enter a span's scope safely. + * closing a nested {@link SpanScope} restores the outer observation and tracing context, opening a scope after + * {@code end()} does not throw, and {@link Span#runInScope} closes the scope even when the action throws. These + * properties are what let log sites in both the sync and the async driver re-enter a span's scope safely. */ class MicrometerSpanScopeTest { @@ -54,81 +49,39 @@ void nestedScopesRestoreTheOuterScope() { TracingObservationHandler.TracingContext tracingContext = observation.getContextView().get(TracingObservationHandler.TracingContext.class); io.micrometer.tracing.Span observationSpan = tracingContext.getSpan(); - MicrometerTracer.MicrometerSpan span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); - assertTrue(span.isThreadLocalEmpty(), "no thread-local entry may exist before the first open"); + Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); - span.openScope(); // outer, e.g. MongoClusterImpl + SpanScope outer = span.openScope(); // outer, e.g. MongoClusterImpl assertSame(observation, registry.getCurrentObservation()); - assertFalse(span.isThreadLocalEmpty(), "an open scope must be tracked"); Observation.Scope outerScope = registry.getCurrentObservationScope(); - span.openScope(); // inner, e.g. DefaultConnectionPool at log time + SpanScope inner = span.openScope(); // inner, e.g. DefaultConnectionPool at log time assertSame(observation, registry.getCurrentObservation()); - span.closeScope(); // inner close + inner.close(); assertSame(observation, registry.getCurrentObservation(), "the observation must still be current after the inner close"); assertSame(outerScope, registry.getCurrentObservationScope(), "the outer scope itself must be current"); assertSame(observationSpan, tracer.currentSpan(), "the observation's span must still be current after the inner close"); - span.closeScope(); // outer close - assertNull(registry.getCurrentObservation(), "no observation may remain current after balanced closes"); - assertNull(tracer.currentSpan(), "no span may remain current after balanced closes"); - assertTrue(span.isThreadLocalEmpty(), "a balanced open/close must clear the thread-local"); + outer.close(); + assertNull(registry.getCurrentObservation(), "no observation may remain current after both scopes close"); + assertNull(tracer.currentSpan(), "no span may remain current after both scopes close"); observation.stop(); } @Test - void aThreadsCloseDoesNotCloseAnotherThreadsScope() throws Exception { - TestObservationRegistry registry = TestObservationRegistry.create(); - Observation outer = Observation.start("outer", registry); - Observation observation = Observation.start("op", registry); - Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); - - Observation.Scope outerScope = outer.openScope(); // thread A already has an outer observation current - span.openScope(); // thread A opens the span scope; its previous observation is outer - assertSame(observation, registry.getCurrentObservation()); - - ExecutorService threadB = Executors.newSingleThreadExecutor(); - try { - threadB.submit(() -> span.openScope()).get(); // thread B opens its own scope and keeps it open - - span.closeScope(); // thread A closes while thread B's scope is still open - assertSame(outer, registry.getCurrentObservation(), - "thread A's close must restore thread A's previous observation"); - - threadB.submit(() -> { - assertSame(observation, registry.getCurrentObservation(), - "thread B's scope must still be open"); - span.closeScope(); - assertNull(registry.getCurrentObservation(), "thread B leaves no scope open on its thread"); - }).get(); - } finally { - threadB.shutdown(); - } - outerScope.close(); - assertNull(registry.getCurrentObservation(), "thread A leaves no scope open on its thread"); - outer.stop(); - observation.stop(); - } - - @Test - void closeWithoutOpenAndOpenAfterEndAreSafe() { + void openScopeAfterEndDoesNotThrow() { ObservationRegistry registry = TestObservationRegistry.create(); Observation observation = Observation.start("op", registry); - MicrometerTracer.MicrometerSpan span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); - - span.closeScope(); // nothing open: must be a no-op - assertNull(registry.getCurrentObservation(), "an unmatched close must not change the current observation"); - assertTrue(span.isThreadLocalEmpty(), "an unmatched close must not create a thread-local entry"); + Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); span.end(); - assertDoesNotThrow(span::openScope); - assertDoesNotThrow(span::closeScope); - assertTrue(span.isThreadLocalEmpty(), "a balanced open/close after end must clear the thread-local"); + assertDoesNotThrow(() -> span.openScope().close()); + assertNull(registry.getCurrentObservation(), "no observation may remain current after the scope closes"); } @Test void runInScopeClosesTheScopeWhenTheActionThrows() { ObservationRegistry registry = TestObservationRegistry.create(); Observation observation = Observation.start("op", registry); - MicrometerTracer.MicrometerSpan span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); + Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); RuntimeException failure = new RuntimeException("appender failed"); RuntimeException thrown = assertThrows(RuntimeException.class, () -> Span.runInScope(span, () -> { @@ -137,7 +90,6 @@ void runInScopeClosesTheScopeWhenTheActionThrows() { assertSame(failure, thrown, "the action's exception must propagate unchanged"); assertNull(registry.getCurrentObservation(), "the scope must be closed when the action throws"); - assertTrue(span.isThreadLocalEmpty(), "the failed action must not leave a thread-local entry"); AtomicBoolean ran = new AtomicBoolean(); Span.runInScope(null, () -> ran.set(true)); diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTraceParentTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTraceParentTest.java index 8cb3a670d1..ba52f04707 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTraceParentTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTraceParentTest.java @@ -136,7 +136,7 @@ protected Class loadClass(final String name, final boolean resolve) throws Cl Class spanInterface = Class.forName( "com.mongodb.internal.observability.micrometer.Span", true, isolatedLoader); - spanInterface.getMethod("openScope").invoke(span); + Object scope = spanInterface.getMethod("openScope").invoke(span); Object traceContext = assertDoesNotThrow(() -> spanInterface.getMethod("context").invoke(span), "obtaining the trace context must not throw when micrometer-tracing is absent"); @@ -149,7 +149,8 @@ protected Class loadClass(final String name, final boolean resolve) throws Cl assertNull(traceParent); - spanInterface.getMethod("closeScope").invoke(span); + Class.forName("com.mongodb.internal.observability.micrometer.SpanScope", true, isolatedLoader) + .getMethod("close").invoke(scope); spanInterface.getMethod("end").invoke(span); } } @@ -161,15 +162,13 @@ private static String traceParentFor(final String traceId, final String spanId, MicrometerTracer micrometerTracer = new MicrometerTracer(registry, false, 1000, null); Span span = micrometerTracer.nextSpan(MongodbObservation.MONGODB_COMMAND, "find", null, null); - span.openScope(); - try { + try (SpanScope ignored = span.openScope()) { SimpleTraceContext context = (SimpleTraceContext) tracer.lastSpan().context(); context.setTraceId(traceId); context.setSpanId(spanId); context.setSampled(sampled); return span.context().traceParent(); } finally { - span.closeScope(); span.end(); } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTracerRecordingTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTracerRecordingTest.java index 9521b1f7dd..6f3e533fe0 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTracerRecordingTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTracerRecordingTest.java @@ -78,7 +78,7 @@ void droppedSpanStillPropagatesValidUnsampledTraceParent() { ObservationRegistry registry = registryWithSampler(Sampler.alwaysOff()); MicrometerTracer tracer = new MicrometerTracer(registry, false, 1000, null); Span span = tracer.nextSpan(MongodbObservation.MONGODB_COMMAND, "find", null, null); - span.openScope(); + SpanScope scope = span.openScope(); try { String traceParent = span.context().traceParent(); assertNotNull(traceParent, "an unsampled span still has a valid context to propagate"); @@ -87,7 +87,7 @@ void droppedSpanStillPropagatesValidUnsampledTraceParent() { assertTrue(traceParent.endsWith("-00"), "trace-flags must be 00 for an unsampled span"); assertFalse(traceParent.substring(3, 35).matches("0+"), "trace id must not be all zeroes"); } finally { - span.closeScope(); + scope.close(); span.end(); } } @@ -128,8 +128,7 @@ private static MongodbObservationContext runCommandSpan(final ObservationRegistr context.setServerAddress(new ServerAddress("localhost", 27017)); context.setConnectionId(new ConnectionId(new ServerId(new ClusterId(), new ServerAddress()), 3, 42L)); context.setQueryText("{find: 'coll'}"); - span.openScope(); - span.closeScope(); + span.openScope().close(); span.end(); return context; } diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java index 11579f86e4..9052670411 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java @@ -53,6 +53,7 @@ import com.mongodb.internal.connection.OperationContext; import com.mongodb.internal.connection.ReadConcernAwareNoOpSessionContext; import com.mongodb.internal.observability.micrometer.Span; +import com.mongodb.internal.observability.micrometer.SpanScope; import com.mongodb.internal.observability.micrometer.TracingManager; import com.mongodb.internal.operation.OperationHelper; import com.mongodb.internal.operation.Operations; @@ -441,9 +442,10 @@ public T execute(final ReadOperation operation, final ReadPreference r ReadBinding binding = getReadBinding(readPreference, actualClientSession, implicitSession); Span span = operationContext.getTracingManager().createOperationSpan( actualClientSession.getTransactionSpan(), operationContext, operation.getCommandName(), operation.getNamespace()); + SpanScope scope = SpanScope.NO_OP; try { if (span != null) { - span.openScope(); + scope = span.openScope(); } if (actualClientSession.hasActiveTransaction() && !binding.getReadPreference().equals(primary())) { throw new MongoClientException("Read preference in a transaction must be primary"); @@ -459,8 +461,8 @@ public T execute(final ReadOperation operation, final ReadPreference r throw e; } finally { binding.release(); + scope.close(); if (span != null) { - span.closeScope(); span.end(); } } @@ -479,9 +481,10 @@ public T execute(final WriteOperation operation, final ReadConcern readCo WriteBinding binding = getWriteBinding(actualClientSession, isImplicitSession(session)); Span span = operationContext.getTracingManager().createOperationSpan( actualClientSession.getTransactionSpan(), operationContext, operation.getCommandName(), operation.getNamespace()); + SpanScope scope = SpanScope.NO_OP; try { if (span != null) { - span.openScope(); + scope = span.openScope(); } return operation.execute(binding, operationContext); } catch (MongoException e) { @@ -494,8 +497,8 @@ public T execute(final WriteOperation operation, final ReadConcern readCo throw e; } finally { binding.release(); + scope.close(); if (span != null) { - span.closeScope(); span.end(); } } From 9bc5ebd122c21a19afdec2132fe2b4288bd743e9 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 26 Nov 2026 00:24:38 +0000 Subject: [PATCH 33/36] JAVA-5734 Keep only the prose tests for log/trace correlation Prose Tests 10-13 run on both drivers and cover every log site end to end. The unit tests added along the way asserted either Micrometer's own scope contract or sites the prose tests already check; the one case they alone covered, connection reuse across operations, is now asserted in prose Test 12 (the commit's check-in carries the commit's operation span). --- .../DefaultConnectionPoolLogScopeTest.java | 156 ------------------ .../InternalStreamConnectionTracingTest.java | 79 --------- .../micrometer/MicrometerSpanScopeTest.java | 99 ----------- .../client/AbstractMicrometerProseTest.java | 9 +- 4 files changed, 8 insertions(+), 335 deletions(-) delete mode 100644 driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java delete mode 100644 driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java deleted file mode 100644 index d3b9618034..0000000000 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolLogScopeTest.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.internal.connection; - -import com.mongodb.MongoNamespace; -import com.mongodb.ServerAddress; -import com.mongodb.connection.ClusterId; -import com.mongodb.connection.ConnectionPoolSettings; -import com.mongodb.connection.ServerId; -import com.mongodb.internal.inject.SameObjectProvider; -import com.mongodb.internal.logging.LogMessage; -import com.mongodb.internal.observability.micrometer.Span; -import com.mongodb.internal.observability.micrometer.SpanScope; -import com.mongodb.internal.observability.micrometer.TraceContext; -import com.mongodb.lang.Nullable; -import com.mongodb.logging.TestLoggingInterceptor; -import com.mongodb.observability.micrometer.MongodbObservationContext; -import org.bson.BsonDocument; -import org.junit.jupiter.api.Test; - -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; - -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT_FACTORY; -import static com.mongodb.ClusterFixture.createOperationContext; -import static com.mongodb.internal.logging.LogMessage.Component.CONNECTION; -import static com.mongodb.internal.logging.LogMessage.Level.DEBUG; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; - -/** - * Verifies that the "Connection checked in" log message is emitted while the span of the most recent checkout is - * open, so an MDC bridge reading the current span at log time attributes it to the right operation. A real pool - * with a test connection factory is driven through two checkouts of the same connection, with fake spans that - * count scope opens and closes. This covers connection reuse, which the end-to-end prose tests do not. - */ -final class DefaultConnectionPoolLogScopeTest { - - @Test - void checkedInMessageUsesTheSpanOfTheMostRecentCheckout() { - String applicationName = "DefaultConnectionPoolLogScopeTest2"; - ServerId serverId = new ServerId(new ClusterId(applicationName), new ServerAddress()); - ScopeCountingSpan firstSpan = new ScopeCountingSpan(); - ScopeCountingSpan secondSpan = new ScopeCountingSpan(); - OperationContext first = createOperationContext(); - first.setTracingSpan(firstSpan); - OperationContext second = createOperationContext(); - second.setTracingSpan(secondSpan); - DefaultConnectionPool pool = new DefaultConnectionPool(serverId, new TestInternalConnectionFactory(), - ConnectionPoolSettings.builder().maxSize(1).build(), - SameObjectProvider.initialized(mock(SdamServerDescriptionManager.class)), OPERATION_CONTEXT_FACTORY); - pool.ready(); - - try (ScopeRecordingInterceptor interceptor = new ScopeRecordingInterceptor(applicationName, secondSpan)) { - pool.get(first).close(); - interceptor.scopeOpenAtMessage.clear(); - int firstSpanOpensBeforeSecondCheckout = firstSpan.openCount.get(); - pool.get(second).close(); - - interceptor.assertEmittedInsideScope("Connection checked in"); // must use the second checkout's span - assertEquals(firstSpanOpensBeforeSecondCheckout, firstSpan.openCount.get(), - "the first checkout's span must not be re-entered by the second checkout"); - assertEquals(0, firstSpan.openCount.get() - firstSpan.closeCount.get()); - } finally { - pool.close(); - } - } - - private static final class ScopeRecordingInterceptor extends TestLoggingInterceptor { - private final ScopeCountingSpan span; - private final Map scopeOpenAtMessage = new ConcurrentHashMap<>(); - - ScopeRecordingInterceptor(final String applicationName, final ScopeCountingSpan span) { - super(applicationName, new LoggingFilter(Collections.singletonMap(CONNECTION, DEBUG))); - this.span = span; - } - - @Override - public synchronized void intercept(final LogMessage message) { - super.intercept(message); - scopeOpenAtMessage.put(message.getMessageId(), span.isScopeOpen()); - } - - void assertEmittedInsideScope(final String messageId) { - Boolean scopeOpen = scopeOpenAtMessage.get(messageId); - assertNotNull(scopeOpen, messageId + " was not emitted"); - assertTrue(scopeOpen, messageId + " must be emitted inside the span scope"); - } - } - - static final class ScopeCountingSpan implements Span { - private final AtomicInteger openCount = new AtomicInteger(); - private final AtomicInteger closeCount = new AtomicInteger(); - - boolean isScopeOpen() { - return openCount.get() > closeCount.get(); - } - - @Override - public SpanScope openScope() { - openCount.incrementAndGet(); - return closeCount::incrementAndGet; - } - - @Override - public void setQueryText(final BsonDocument commandDocument) { - } - - @Override - public void event(final String event) { - } - - @Override - public void error(final Throwable throwable) { - } - - @Override - public void end() { - } - - @Override - public TraceContext context() { - return TraceContext.EMPTY; - } - - @Override - @Nullable - public MongodbObservationContext getMongodbObservationContext() { - return null; - } - - @Override - @Nullable - public MongoNamespace getNamespace() { - return null; - } - } -} diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java index 3d460a33f4..8d2b43a755 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java @@ -20,10 +20,6 @@ import com.mongodb.MongoNamespace; import com.mongodb.async.FutureResultCallback; import com.mongodb.connection.AsyncCompletionHandler; -import com.mongodb.event.CommandFailedEvent; -import com.mongodb.event.CommandListener; -import com.mongodb.event.CommandStartedEvent; -import com.mongodb.event.CommandSucceededEvent; import com.mongodb.internal.IgnorableRequestContext; import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.TimeoutSettings; @@ -44,13 +40,9 @@ import org.bson.codecs.BsonDocumentCodec; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; import java.io.ByteArrayOutputStream; import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -259,77 +251,6 @@ void asyncUnacknowledgedSendAttachesTelemetrySectionAndEndsSpanOnce() { connection.close(); } - /** Records whether the command span scope was open on the emitting thread when each command event fired. */ - private static final class ScopeObservingListener implements CommandListener { - private final RecordingSpan span; - private final Map scopeOpenAtEvent = new ConcurrentHashMap<>(); - - ScopeObservingListener(final RecordingSpan span) { - this.span = span; - } - - private void record(final String event) { - scopeOpenAtEvent.put(event, span.openScopeCount.get() > span.scopeCloseCount.get()); - } - - @Override - public void commandStarted(final CommandStartedEvent event) { - record("started"); - } - - @Override - public void commandSucceeded(final CommandSucceededEvent event) { - record("succeeded"); - } - - @Override - public void commandFailed(final CommandFailedEvent event) { - record("failed"); - } - } - - @ParameterizedTest(name = "async={0}") - @ValueSource(booleans = {false, true}) - @DisplayName("Started and succeeded command events fire while the command span scope is open") - void commandEventsFireInsideSpanScope(final boolean async) throws Exception { - AtomicInteger readCallCount = new AtomicInteger(); - CapturingTestStream stream = new CapturingTestStream() { - private ByteBuf nextResponseChunk() { - return readCallCount.incrementAndGet() == 1 - ? createValidResponseHeader(getCommandMessageId()) - : createResponseBody(new BsonDocument("ok", new BsonInt32(1))); - } - - @Override - public ByteBuf read(final int numBytes, final OperationContext operationContext) { - return nextResponseChunk(); - } - - @Override - public void readAsync(final int numBytes, final OperationContext operationContext, - final AsyncCompletionHandler handler) { - handler.completed(nextResponseChunk()); - } - }; - RecordingSpan span = new RecordingSpan(); - ScopeObservingListener listener = new ScopeObservingListener(span); - InternalStreamConnection connection = createOpenConnection(stream, listener); - CommandMessage commandMessage = createPingCommand(); - stream.setCommandMessageId(commandMessage.getId()); - if (async) { - FutureResultCallback callback = new FutureResultCallback<>(); - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), createTracedOperationContext(span), callback); - callback.get(5, TimeUnit.SECONDS); - } else { - connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), createTracedOperationContext(span)); - } - assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("started"), "started event must see the span scope"); - assertEquals(Boolean.TRUE, listener.scopeOpenAtEvent.get("succeeded"), "succeeded event must see the span scope"); - assertEquals(span.openScopeCount.get(), span.scopeCloseCount.get(), "scopes must be balanced"); - assertEquals(1, span.endCount.get()); - connection.close(); - } - private static CommandMessage createUnacknowledgedInsertCommand() { BsonDocument insert = new BsonDocument("insert", new BsonString("coll")) .append("documents", new BsonArray(singletonList(new BsonDocument("_id", new BsonInt32(1))))) diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java deleted file mode 100644 index c7e7d6d87a..0000000000 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.internal.observability.micrometer; - -import io.micrometer.observation.Observation; -import io.micrometer.observation.ObservationRegistry; -import io.micrometer.observation.tck.TestObservationRegistry; -import io.micrometer.tracing.handler.DefaultTracingObservationHandler; -import io.micrometer.tracing.handler.TracingObservationHandler; -import io.micrometer.tracing.test.simple.SimpleTracer; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.atomic.AtomicBoolean; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Verifies the scope contract of {@link MicrometerTracer.MicrometerSpan} against a real Micrometer registry: - * closing a nested {@link SpanScope} restores the outer observation and tracing context, opening a scope after - * {@code end()} does not throw, and {@link Span#runInScope} closes the scope even when the action throws. These - * properties are what let log sites in both the sync and the async driver re-enter a span's scope safely. - */ -class MicrometerSpanScopeTest { - - @Test - void nestedScopesRestoreTheOuterScope() { - ObservationRegistry registry = ObservationRegistry.create(); - SimpleTracer tracer = new SimpleTracer(); - registry.observationConfig().observationHandler(new DefaultTracingObservationHandler(tracer)); - Observation observation = Observation.start("op", registry); - TracingObservationHandler.TracingContext tracingContext = - observation.getContextView().get(TracingObservationHandler.TracingContext.class); - io.micrometer.tracing.Span observationSpan = tracingContext.getSpan(); - Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); - - SpanScope outer = span.openScope(); // outer, e.g. MongoClusterImpl - assertSame(observation, registry.getCurrentObservation()); - Observation.Scope outerScope = registry.getCurrentObservationScope(); - SpanScope inner = span.openScope(); // inner, e.g. DefaultConnectionPool at log time - assertSame(observation, registry.getCurrentObservation()); - inner.close(); - assertSame(observation, registry.getCurrentObservation(), "the observation must still be current after the inner close"); - assertSame(outerScope, registry.getCurrentObservationScope(), "the outer scope itself must be current"); - assertSame(observationSpan, tracer.currentSpan(), "the observation's span must still be current after the inner close"); - outer.close(); - assertNull(registry.getCurrentObservation(), "no observation may remain current after both scopes close"); - assertNull(tracer.currentSpan(), "no span may remain current after both scopes close"); - observation.stop(); - } - - @Test - void openScopeAfterEndDoesNotThrow() { - ObservationRegistry registry = TestObservationRegistry.create(); - Observation observation = Observation.start("op", registry); - Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); - - span.end(); - assertDoesNotThrow(() -> span.openScope().close()); - assertNull(registry.getCurrentObservation(), "no observation may remain current after the scope closes"); - } - - @Test - void runInScopeClosesTheScopeWhenTheActionThrows() { - ObservationRegistry registry = TestObservationRegistry.create(); - Observation observation = Observation.start("op", registry); - Span span = new MicrometerTracer.MicrometerSpan(observation, null, Integer.MAX_VALUE); - RuntimeException failure = new RuntimeException("appender failed"); - - RuntimeException thrown = assertThrows(RuntimeException.class, () -> Span.runInScope(span, () -> { - throw failure; - })); - - assertSame(failure, thrown, "the action's exception must propagate unchanged"); - assertNull(registry.getCurrentObservation(), "the scope must be closed when the action throws"); - - AtomicBoolean ran = new AtomicBoolean(); - Span.runInScope(null, () -> ran.set(true)); - assertTrue(ran.get(), "a null span must run the action without opening a scope"); - observation.stop(); - } -} diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java index 1d8d125f7b..a1ac4d4afc 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java @@ -453,7 +453,6 @@ public KeyValues getLowCardinalityKeyValues(final MongodbObservationContext cont @DisplayName("Test 10: Command log messages carry their own command span") @Test void testCommandLogMessagesCarryTheirOwnCommandSpan() { - // the fail point is scoped by appName, which requires MongoDB 4.4; on a sharded cluster the fixture URI names one mongos assumeTrue(serverVersionAtLeast(4, 4)); String appName = "otel-log-test10"; BsonDocument failPoint = BsonDocument.parse("{ configureFailPoint: 'failCommand', mode: { times: 1 }," @@ -650,6 +649,14 @@ void testLogMessagesInsideTransaction() { assertTrue(operationSpanIds.contains(l.spanId), messageId + " must carry an operation span of the transaction"); } } + + // the commit reuses the pooled connection the insert checked in, so its "Connection checked in" must carry the + // commit's operation span, not the span captured when the insert checked the connection out + FinishedSpan commitOperation = spans.stream() + .filter(s -> transaction.getSpanId().equals(s.getParentId()) && s.getName().startsWith("commitTransaction")) + .findFirst().orElseThrow(() -> new AssertionError("commitTransaction operation span not found in " + spans)); + assertTrue(logs.messages("Connection checked in").stream().anyMatch(l -> commitOperation.getSpanId().equals(l.spanId)), + "Connection checked in for the commit must carry the commit operation span"); } } From c32d58e319702b5859f9b2f40ee76abd2b09fe0d Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 26 Nov 2026 14:22:54 +0000 Subject: [PATCH 34/36] JAVA-5734 Drop the dead SRV assumption from the failing-selection prose test The client replaces the fixture's cluster settings entirely, including srvHost, so the test runs on SRV fixtures too. Also drops two stale comments in Tests 10 and 11. --- .../com/mongodb/client/AbstractMicrometerProseTest.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java index a1ac4d4afc..45e4c0a8d1 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java @@ -63,7 +63,6 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; -import static com.mongodb.ClusterFixture.getConnectionString; import static com.mongodb.ClusterFixture.getCredential; import static com.mongodb.ClusterFixture.getDefaultDatabaseName; import static com.mongodb.ClusterFixture.getPrimary; @@ -457,7 +456,6 @@ void testCommandLogMessagesCarryTheirOwnCommandSpan() { String appName = "otel-log-test10"; BsonDocument failPoint = BsonDocument.parse("{ configureFailPoint: 'failCommand', mode: { times: 1 }," + " data: { failCommands: ['find'], errorCode: 91, appName: '" + appName + "' } }"); - // error code 91 marks the server Unknown; a short heartbeat lets the retry rediscover it quickly MongoClientSettings settings = MongoClientSettings.builder(tracedSettings(appName)) .retryReads(true) .applyToServerSettings(b -> b.heartbeatFrequency(500, TimeUnit.MILLISECONDS)) @@ -523,12 +521,11 @@ void testOperationPathLogMessagesCarryTheOperationSpan() { @DisplayName("Test 11 (steps 4-6): Server selection failure log messages carry the operation span") @Test void testServerSelectionFailureLogMessagesCarryTheOperationSpan() { - // a load-balanced fixture would not time out; the SRV assumption keeps the fixture's resolver settings out of the way - assumeFalse(getConnectionString().isSrvProtocol()); + // a load-balanced fixture would not time out assumeFalse(isLoadBalanced()); String operationName = "insert " + getDefaultDatabaseName() + ".test"; String appName = "otel-log-test11-failing"; - // replace the fixture's cluster settings entirely so that the host list does not depend on the fixture URI's shape + // replace the fixture's cluster settings entirely (hosts and any srvHost) with a single unreachable host MongoClientSettings failing = MongoClientSettings.builder(tracedSettings(appName)) .applyToClusterSettings(b -> b.applySettings(ClusterSettings.builder() .hosts(singletonList(new ServerAddress("localhost", 1))) From 9e4a8899962f6a29a6781576cc1763915301ec33 Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 26 Nov 2026 14:31:56 +0000 Subject: [PATCH 35/36] JAVA-5734 Simplify the log/trace correlation prose tests - Exact ordered message lists replace the trace-id filters and non-empty checks - Parent-based span lookups replace name/index lookups and the no-space heuristic - Test 10 gains the spec's "command spans under the operation span" check - Tautological trace checks removed (a child span is in its parent's trace) - Dead helpers (spanNamed, spanIds, heartbeatSucceededSince) removed --- .../client/AbstractMicrometerProseTest.java | 236 ++++++++---------- 1 file changed, 104 insertions(+), 132 deletions(-) diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java index 45e4c0a8d1..bd52c01057 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java @@ -458,6 +458,7 @@ void testCommandLogMessagesCarryTheirOwnCommandSpan() { + " data: { failCommands: ['find'], errorCode: 91, appName: '" + appName + "' } }"); MongoClientSettings settings = MongoClientSettings.builder(tracedSettings(appName)) .retryReads(true) + // error 91 marks the server Unknown; without a fast heartbeat the retry waits ~10 s for rediscovery .applyToServerSettings(b -> b.heartbeatFrequency(500, TimeUnit.MILLISECONDS)) .build(); try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); @@ -467,30 +468,14 @@ void testCommandLogMessagesCarryTheirOwnCommandSpan() { assertNoSpanIsCurrent(); List spans = inMemoryOtel.getFinishedSpans(); - FinishedSpan firstAttempt = spanNamed(spans, "find", 0); - FinishedSpan secondAttempt = spanNamed(spans, "find", 1); - FinishedSpan operation = spanNamed(spans, "find " + getDefaultDatabaseName() + ".test", 0); - - List started = logs.messages("Command started").stream() - .filter(l -> operation.getTraceId().equals(l.traceId)).collect(Collectors.toList()); - assertEquals(2, started.size(), "one started message per attempt"); - assertEquals(firstAttempt.getSpanId(), started.get(0).spanId); - assertEquals(secondAttempt.getSpanId(), started.get(1).spanId); - - List failed = logs.messages("Command failed"); - assertEquals(1, failed.size()); - assertEquals(firstAttempt.getSpanId(), failed.get(0).spanId); - assertEquals(firstAttempt.getTraceId(), failed.get(0).traceId); - - List succeeded = logs.messages("Command succeeded").stream() - .filter(l -> secondAttempt.getTraceId().equals(l.traceId)).collect(Collectors.toList()); - assertEquals(1, succeeded.size()); - assertEquals(secondAttempt.getSpanId(), succeeded.get(0).spanId); - assertEquals(secondAttempt.getTraceId(), succeeded.get(0).traceId); - - for (ObservedLog l : logs.component(LogMessage.Component.COMMAND)) { - assertNotEquals(operation.getSpanId(), l.spanId, "command messages must not carry the operation span"); - } + FinishedSpan operation = onlySpanNamed(spans, operationSpanName("find")); + // command spans finish in attempt order + List attempts = childSpans(spans, operation, "find"); + assertEquals(2, attempts.size(), "two find attempts expected under " + operation); + // exact equality to a command span also means that none of these messages carries the operation span + assertCarry(logs.messages("Command started"), attempts.get(0), attempts.get(1)); + assertCarry(logs.messages("Command failed"), attempts.get(0)); + assertCarry(logs.messages("Command succeeded"), attempts.get(1)); } } @@ -498,32 +483,23 @@ void testCommandLogMessagesCarryTheirOwnCommandSpan() { @Test void testOperationPathLogMessagesCarryTheOperationSpan() { assumeFalse(isLoadBalanced()); - String operationName = "insert " + getDefaultDatabaseName() + ".test"; String appName = "otel-log-test11"; try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); MongoClient client = createMongoClient(tracedSettings(appName))) { client.getDatabase(getDefaultDatabaseName()).getCollection("test").insertOne(new Document("x", 1)); assertNoSpanIsCurrent(); - FinishedSpan operation = spanNamed(inMemoryOtel.getFinishedSpans(), operationName, 0); - for (String messageId : asList("Server selection started", "Server selection succeeded", - "Connection checkout started", "Connection checked out", "Connection checked in")) { - List observed = logs.messages(messageId).stream() - .filter(l -> operation.getTraceId().equals(l.traceId)).collect(Collectors.toList()); - assertFalse(observed.isEmpty(), messageId + " must be emitted inside the operation's trace"); - for (ObservedLog l : observed) { - assertEquals(operation.getSpanId(), l.spanId, messageId + " must carry the operation span"); - } - } + FinishedSpan operation = onlySpanNamed(inMemoryOtel.getFinishedSpans(), operationSpanName("insert")); + assertEachCarries(logs, operation, "Server selection started", "Server selection succeeded", + "Connection checkout started", "Connection checked out", "Connection checked in"); } } @DisplayName("Test 11 (steps 4-6): Server selection failure log messages carry the operation span") @Test void testServerSelectionFailureLogMessagesCarryTheOperationSpan() { - // a load-balanced fixture would not time out + // not on load balanced (per spec): a load-balanced client never waits for server selection, so the waiting message is never logged assumeFalse(isLoadBalanced()); - String operationName = "insert " + getDefaultDatabaseName() + ".test"; String appName = "otel-log-test11-failing"; // replace the fixture's cluster settings entirely (hosts and any srvHost) with a single unreachable host MongoClientSettings failing = MongoClientSettings.builder(tracedSettings(appName)) @@ -539,23 +515,17 @@ void testServerSelectionFailureLogMessagesCarryTheOperationSpan() { () -> client.getDatabase(getDefaultDatabaseName()).getCollection("test").insertOne(new Document("x", 1))); assertNoSpanIsCurrent(); - FinishedSpan operation = onlySpanNamed(inMemoryOtel.getFinishedSpans(), operationName); - for (String messageId : asList("Waiting for suitable server to become available", "Server selection failed")) { - List observed = logs.messages(messageId); - assertFalse(observed.isEmpty(), messageId + " must be emitted"); - for (ObservedLog l : observed) { - assertEquals(operation.getTraceId(), l.traceId, messageId + " must carry the operation's trace"); - assertEquals(operation.getSpanId(), l.spanId, messageId + " must carry the operation span"); - } - } + FinishedSpan operation = onlySpanNamed(inMemoryOtel.getFinishedSpans(), operationSpanName("insert")); + assertEachCarries(logs, operation, "Waiting for suitable server to become available", "Server selection failed"); } } @DisplayName("Test 11 (steps 7-10): Connection checkout failure log messages carry the operation span") @Test void testConnectionCheckoutFailureLogMessagesCarryTheOperationSpan() { + // not on load balanced (per spec): the fail point is set on one mongos, but the load balancer may route the client to another assumeFalse(isLoadBalanced()); - // only SCRAM sends saslContinue as a standalone command; a null mechanism negotiates SCRAM + // only SCRAM (default) sends saslContinue as a standalone command MongoCredential credential = getCredential(); assumeTrue(credential != null); assumeTrue(credential.getAuthenticationMechanism() == null @@ -576,15 +546,8 @@ void testConnectionCheckoutFailureLogMessagesCarryTheOperationSpan() { assertThrows(MongoException.class, () -> client.getDatabase(getDefaultDatabaseName()).getCollection("test").find().first()); assertNoSpanIsCurrent(); - FinishedSpan operation = onlySpanNamed(inMemoryOtel.getFinishedSpans(), "find " + getDefaultDatabaseName() + ".test"); - for (String messageId : asList("Connection checkout started", "Connection checkout failed")) { - List observed = logs.messages(messageId); - assertFalse(observed.isEmpty(), messageId + " must be emitted"); - for (ObservedLog l : observed) { - assertEquals(operation.getTraceId(), l.traceId, messageId + " must carry the operation's trace"); - assertEquals(operation.getSpanId(), l.spanId, messageId + " must carry the operation span"); - } - } + FinishedSpan operation = onlySpanNamed(inMemoryOtel.getFinishedSpans(), operationSpanName("find")); + assertEachCarries(logs, operation, "Connection checkout started", "Connection checkout failed"); } } @@ -601,74 +564,37 @@ void testLogMessagesInsideTransaction() { assertNoSpanIsCurrent(); List spans = inMemoryOtel.getFinishedSpans(); - FinishedSpan transaction = spanNamed(spans, "transaction", 0); - FinishedSpan insertOperation = spanNamed(spans, "insert " + getDefaultDatabaseName() + ".test", 0); - assertEquals(transaction.getSpanId(), insertOperation.getParentId(), "the insert operation must run under the transaction"); - FinishedSpan insertCommand = spanNamed(spans, "insert", 0); - assertEquals(insertOperation.getSpanId(), insertCommand.getParentId(), "the insert command must run under its operation"); - FinishedSpan commitCommand = spanNamed(spans, "commitTransaction", 0); - for (FinishedSpan command : asList(insertCommand, commitCommand)) { - assertEquals(transaction.getTraceId(), command.getTraceId(), command.getName() + " must be in the transaction's trace"); - for (String messageId : asList("Command started", "Command succeeded")) { - List observed = logs.messages(messageId).stream() - .filter(l -> command.getSpanId().equals(l.spanId)).collect(Collectors.toList()); - assertEquals(1, observed.size(), messageId + " must carry the " + command.getName() + " command span"); - assertEquals(transaction.getTraceId(), observed.get(0).traceId, - messageId + " for " + command.getName() + " must carry the transaction's trace"); - } - } - - // command spans are named after the command alone; operation spans add the namespace - Set commandSpanIds = spans.stream() - .filter(s -> transaction.getTraceId().equals(s.getTraceId())) - .filter(s -> !s.getName().equals("transaction") && !s.getName().contains(" ")) - .map(FinishedSpan::getSpanId).collect(Collectors.toSet()); - for (ObservedLog l : logs.component(LogMessage.Component.COMMAND)) { - if (transaction.getTraceId().equals(l.traceId)) { - assertNotEquals(transaction.getSpanId(), l.spanId, l.messageId + " must not carry the transaction span"); - assertTrue(commandSpanIds.contains(l.spanId), l.messageId + " must carry a command span of the transaction"); - } - } - - // server selection and connection checkout precede any command span, so they belong to the operation span; every - // operation of the transaction (the insert and the commit) is a child of the transaction span - Set operationSpanIds = spans.stream() - .filter(s -> transaction.getSpanId().equals(s.getParentId())) - .map(FinishedSpan::getSpanId).collect(Collectors.toSet()); + FinishedSpan transaction = onlySpanNamed(spans, "transaction"); + FinishedSpan insertOperation = childSpan(spans, transaction, operationSpanName("insert")); + FinishedSpan insertCommand = childSpan(spans, insertOperation, "insert"); + // admin commands have no collection in the operation span name + FinishedSpan commitOperation = childSpan(spans, transaction, "commitTransaction admin"); + FinishedSpan commitCommand = childSpan(spans, commitOperation, "commitTransaction"); + assertCarry(logs.messages("Command started"), insertCommand, commitCommand); + assertCarry(logs.messages("Command succeeded"), insertCommand, commitCommand); + + // server selection and connection checkout precede any command span, so they belong to the operation span of the + // insert or of the commit; neither is the transaction span + Set operationSpanIds = new HashSet<>(asList(insertOperation.getSpanId(), commitOperation.getSpanId())); for (String messageId : asList("Server selection started", "Server selection succeeded", "Connection checkout started", "Connection checked out", "Connection checked in")) { - List observed = logs.messages(messageId).stream() - .filter(l -> transaction.getTraceId().equals(l.traceId)).collect(Collectors.toList()); + List observed = logs.messages(messageId); assertTrue(observed.stream().anyMatch(l -> insertOperation.getSpanId().equals(l.spanId)), - messageId + " must be emitted for the insert carrying the insert operation span, but got " + spanIds(observed)); + messageId + " must be emitted for the insert carrying its operation span, got " + observed); for (ObservedLog l : observed) { - assertNotEquals(transaction.getSpanId(), l.spanId, messageId + " must not carry the transaction span"); - assertTrue(operationSpanIds.contains(l.spanId), messageId + " must carry an operation span of the transaction"); + assertEquals(transaction.getTraceId(), l.traceId, messageId + " must carry the transaction's trace, got " + l); + assertTrue(operationSpanIds.contains(l.spanId), + messageId + " must carry an operation span of the transaction, got " + l); } } // the commit reuses the pooled connection the insert checked in, so its "Connection checked in" must carry the // commit's operation span, not the span captured when the insert checked the connection out - FinishedSpan commitOperation = spans.stream() - .filter(s -> transaction.getSpanId().equals(s.getParentId()) && s.getName().startsWith("commitTransaction")) - .findFirst().orElseThrow(() -> new AssertionError("commitTransaction operation span not found in " + spans)); assertTrue(logs.messages("Connection checked in").stream().anyMatch(l -> commitOperation.getSpanId().equals(l.spanId)), "Connection checked in for the commit must carry the commit operation span"); } } - /** - * Runs {@code body} in a transaction on {@code session}, as the spec's {@code withTransaction} step requires. - */ - protected void runInTransaction(final ClientSession session, final Runnable body) { - session.withTransaction(() -> { - body.run(); - return null; - }); - } - - // Tests 14 and 15 apply only to driver-managed log output and are not applicable to Java: the driver logs through SLF4J and - // has no driver-managed log destinations. The reactive subclass runs Tests 10 to 13 as the asynchronous API. @DisplayName("Test 13: Background log messages are not attributed to an operation") @Test void testBackgroundLogMessagesAreNotAttributedToAnOperation() throws InterruptedException { @@ -685,31 +611,29 @@ void testBackgroundLogMessagesAreNotAttributedToAnOperation() throws Interrupted int topologyMessagesBefore = logs.component(LogMessage.Component.TOPOLOGY).size(); // a fixed delay is not sufficient: without a heartbeat message after the operation there is nothing to check - long deadline = System.currentTimeMillis() + 10_000; - while (!heartbeatSucceededSince(logs, topologyMessagesBefore) && System.currentTimeMillis() < deadline) { - Thread.sleep(50); - } - assertTrue(heartbeatSucceededSince(logs, topologyMessagesBefore), + assertTrue(awaitTopologyMessage(logs, topologyMessagesBefore, "Server heartbeat succeeded"), "a \"Server heartbeat succeeded\" message must have been logged after the operation"); - FinishedSpan operation = spanNamed(inMemoryOtel.getFinishedSpans(), "insert " + getDefaultDatabaseName() + ".test", 0); - String operationTraceId = operation.getTraceId(); - Set operationSpanIds = inMemoryOtel.getFinishedSpans().stream() - .filter(s -> operationTraceId.equals(s.getTraceId())) - .map(FinishedSpan::getSpanId).collect(Collectors.toSet()); + String operationTraceId = onlySpanNamed(inMemoryOtel.getFinishedSpans(), operationSpanName("insert")).getTraceId(); List topology = logs.component(LogMessage.Component.TOPOLOGY); for (ObservedLog l : topology.subList(topologyMessagesBefore, topology.size())) { + // trace id and span id come from the same current-span context, so this covers both spec clauses assertNotEquals(operationTraceId, l.traceId, l.messageId + " must not carry the operation's trace"); - assertFalse(l.spanId != null && operationSpanIds.contains(l.spanId), - l.messageId + " must not carry a span of the operation"); } } } - private static boolean heartbeatSucceededSince(final SpanRecordingInterceptor logs, final int topologyMessagesBefore) { - List topology = logs.component(LogMessage.Component.TOPOLOGY); - return topology.subList(topologyMessagesBefore, topology.size()).stream() - .anyMatch(l -> l.messageId.equals("Server heartbeat succeeded")); + // Tests 14 and 15 apply only to driver-managed log output and are not applicable to Java: the driver logs through SLF4J and + // has no driver-managed log destinations. The reactive subclass runs Tests 10 to 13 as the asynchronous API. + + /** + * Runs {@code body} in a transaction on {@code session}, as the spec's {@code withTransaction} step requires. + */ + protected void runInTransaction(final ClientSession session, final Runnable body) { + session.withTransaction(() -> { + body.run(); + return null; + }); } private MongoClientSettings tracedSettings(final String applicationName) { @@ -728,10 +652,8 @@ private void assertNoSpanIsCurrent() { assertNull(observationRegistry.getCurrentObservation(), "no observation may be current after the operation"); } - private static FinishedSpan spanNamed(final List spans, final String name, final int index) { - List matching = spans.stream().filter(s -> s.getName().equals(name)).collect(Collectors.toList()); - assertTrue(matching.size() > index, "expected at least " + (index + 1) + " spans named " + name + " but got " + matching); - return matching.get(index); + private String operationSpanName(final String command) { + return command + " " + getDefaultDatabaseName() + ".test"; } private static FinishedSpan onlySpanNamed(final List spans, final String name) { @@ -740,8 +662,53 @@ private static FinishedSpan onlySpanNamed(final List spans, final return matching.get(0); } - private static List spanIds(final List logs) { - return logs.stream().map(l -> l.spanId).collect(Collectors.toList()); + private static List childSpans(final List spans, final FinishedSpan parent, final String name) { + return spans.stream() + .filter(s -> parent.getSpanId().equals(s.getParentId()) && s.getName().equals(name)) + .collect(Collectors.toList()); + } + + private static FinishedSpan childSpan(final List spans, final FinishedSpan parent, final String name) { + List matching = childSpans(spans, parent, name); + assertEquals(1, matching.size(), "expected exactly one span named " + name + " under " + parent + " but got " + matching); + return matching.get(0); + } + + /** Exactly these messages, in emission order, each carrying the trace id and span id of the matching span. */ + private static void assertCarry(final List observed, final FinishedSpan... expected) { + assertTrue(expected.length > 0, "assertCarry needs at least one expected span"); + assertEquals(expected.length, observed.size(), "expected one message per span of " + asList(expected) + " but got " + observed); + for (int i = 0; i < expected.length; i++) { + assertEquals(expected[i].getTraceId(), observed.get(i).traceId, "trace id of message " + i + " in " + observed); + assertEquals(expected[i].getSpanId(), observed.get(i).spanId, "span id of message " + i + " in " + observed); + } + } + + /** Each message id is emitted at least once, and every emission carries {@code span}. */ + private static void assertEachCarries(final SpanRecordingInterceptor logs, final FinishedSpan span, final String... messageIds) { + for (String messageId : messageIds) { + List observed = logs.messages(messageId); + assertFalse(observed.isEmpty(), messageId + " must be emitted"); + for (ObservedLog l : observed) { + assertEquals(span.getTraceId(), l.traceId, messageId + " must carry the trace of " + span + ", got " + l); + assertEquals(span.getSpanId(), l.spanId, messageId + " must carry the span of " + span + ", got " + l); + } + } + } + + private static boolean awaitTopologyMessage(final SpanRecordingInterceptor logs, final int from, final String messageId) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (true) { + List topology = logs.component(LogMessage.Component.TOPOLOGY); + if (topology.subList(from, topology.size()).stream().anyMatch(l -> l.messageId.equals(messageId))) { + return true; + } + if (System.nanoTime() - deadline >= 0) { + return false; + } + Thread.sleep(50); + } } /** Trace id and span id that were current on the thread when a log message was emitted. */ @@ -759,6 +726,11 @@ private static final class ObservedLog { this.traceId = current == null ? null : current.context().traceId(); this.spanId = current == null ? null : current.context().spanId(); } + + @Override + public String toString() { + return messageId + "{traceId=" + traceId + ", spanId=" + spanId + "}"; + } } /** From 37b34a5839c6505df2bdc196755e9418227d714c Mon Sep 17 00:00:00 2001 From: Nabil Hachicha Date: Thu, 3 Dec 2026 14:15:44 +0000 Subject: [PATCH 36/36] JAVA-5734 Isolate span scope handling from throwing ObservationHandlers Micrometer switches the registry's thread-local current scope before notifying handlers of onScopeOpened, and notifies onScopeClosed before restoring the previous scope, both without exception protection. An application ObservationHandler that threw left the thread stuck on an ended span, misparenting later spans on that thread (the caller's thread in sync, transport threads in reactive). When connection logging is enabled, the exception escaping the "Connection checked in" emission also skipped the connection release, leaking the pooled connection. MicrometerSpan now guards openScope and the returned scope's close. On an open failure it closes the partially opened scope (so handlers that did open, such as the tracing handler, undo their state), restores the previous scope and returns a no-op scope; on a close failure it forces the restore of the previous scope. In both cases it records an event on the span (not an error: the database operation did not fail), attaches the exception text to the span as the key-value mongodb.span.scope.failure, and logs a warning with the exception and the traceparent. Failures during the cleanup itself are swallowed and never attached to the handler's exception, so the guard never throws. Only RuntimeException is caught, matching how listener failures are handled; Errors propagate. The warnings go to the new logger org.mongodb.driver.observability, which applications can configure like the driver's other loggers. Reported by Slav Babanin (vbabanin) in the PR 2099 review. --- .../micrometer/MicrometerTracer.java | 90 +++++++- .../MicrometerSpanScopeGuardTest.java | 210 ++++++++++++++++++ .../client/AbstractMicrometerProseTest.java | 62 ++++++ 3 files changed, 358 insertions(+), 4 deletions(-) create mode 100644 driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeGuardTest.java diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java index c6d04286db..db210fe73c 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java @@ -18,6 +18,8 @@ import com.mongodb.internal.VisibleForTesting; import com.mongodb.MongoNamespace; +import com.mongodb.internal.diagnostics.logging.Logger; +import com.mongodb.internal.diagnostics.logging.Loggers; import com.mongodb.lang.Nullable; import com.mongodb.observability.micrometer.DefaultMongodbObservationConvention; import com.mongodb.observability.micrometer.MongodbObservation; @@ -57,10 +59,15 @@ public class MicrometerTracer implements Tracer { @VisibleForTesting(otherwise = PRIVATE) static final boolean MICROMETER_TRACING_ON_CLASSPATH = isMicrometerTracingOnClasspath(); + private static final Logger LOGGER = Loggers.getLogger("observability"); + private final ObservationRegistry observationRegistry; private final boolean allowCommandPayload; private final int textMaxLength; private final ObservationConvention convention; + /** + * Whether a scope failure has already been logged at WARN by this tracer; later ones are logged at DEBUG. + */ private static boolean isMicrometerTracingOnClasspath() { try { @@ -111,7 +118,7 @@ public Span nextSpan(final MongodbObservation observationType, final String name ((MongodbObservationContext) context).setRecording(false); } } - return new MicrometerSpan(started, namespace, textMaxLength); + return new MicrometerSpan(started, observationRegistry, namespace, textMaxLength); } @Override @@ -235,9 +242,16 @@ static String traceParent(final Observation observation) { /** * Represents a Micrometer-based span. + *

+ * Opening and closing its scope is guarded against application {@code ObservationHandler}s that throw; see {@link #openScope()}. + * One residual remains by design: Micrometer stops notifying handlers at the first {@code onScopeClosed} that throws, so a + * tracing handler registered before the throwing one may keep its own thread-local context on this span until an enclosing + * scope closes, although the registry's current scope is restored. + *

*/ static class MicrometerSpan implements Span { private final Observation observation; + private final ObservationRegistry registry; @Nullable private final MongoNamespace namespace; private final int queryTextLength; @@ -246,19 +260,87 @@ static class MicrometerSpan implements Span { * Constructs a new {@link MicrometerSpan} instance with an associated Observation and MongoDB namespace. * * @param observation The Micrometer {@link Observation}, or null if none exists. + * @param registry The registry holding the thread's current observation scope. * @param namespace The MongoDB namespace associated with the span. * @param queryTextLength The maximum length for query text truncation. */ - MicrometerSpan(final Observation observation, @Nullable final MongoNamespace namespace, final int queryTextLength) { + MicrometerSpan(final Observation observation, final ObservationRegistry registry, @Nullable final MongoNamespace namespace, + final int queryTextLength) { this.namespace = namespace; this.observation = observation; + this.registry = registry; this.queryTextLength = queryTextLength; } + /** + * Micrometer switches the registry's current scope before notifying handlers of {@code onScopeOpened}, and notifies + * {@code onScopeClosed} before restoring the previous scope, both without protection. An application + * {@code ObservationHandler} that throws would otherwise leave the thread stuck on this span and abort the driver's + * work around the scope (for example a connection check-in). As with listener failures, a {@link RuntimeException} + * is reported and swallowed; {@link Error}s propagate. + */ @Override public SpanScope openScope() { - Observation.Scope scope = observation.openScope(); - return scope::close; + Observation.Scope previous = registry.getCurrentObservationScope(); + Observation.Scope scope; + try { + scope = observation.openScope(); + } catch (RuntimeException e) { + restoreAfterFailedOpen(previous); + reportScopeFailure("open", e); + return SpanScope.NO_OP; + } + return () -> closeScope(scope, previous); + } + + private void closeScope(final Observation.Scope scope, @Nullable final Observation.Scope previous) { + try { + scope.close(); + } catch (RuntimeException e) { + // Micrometer notifies the handlers before restoring the previous scope, so force the restore. Micrometer also stops + // notifying at the first handler that throws, so a tracing handler registered before the thrower may keep its + // thread-local context on this span until an enclosing scope closes; that residual is accepted. + registry.setCurrentObservationScope(previous); + reportScopeFailure("close", e); + } + } + + private void restoreAfterFailedOpen(@Nullable final Observation.Scope previous) { + Observation.Scope leaked = registry.getCurrentObservationScope(); + try { + // closing the partially opened scope also lets handlers that did open (e.g. the tracing handler's thread-local) undo it. + // It also notifies handlers that never opened; when the same observation is already open in an enclosing scope, such + // a handler may undo the enclosing scope's tracing context for the rest of that scope. This is bounded: nothing stays + // stale once the enclosing scope closes. + if (leaked != null && leaked != previous && leaked.getCurrentObservation() == observation) { + leaked.close(); + } + } catch (RuntimeException closeFailure) { + // the thread-local is still forced back below and the open failure is reported by the caller + LOGGER.trace("Ignoring a failure while closing a partially opened span scope", closeFailure); + } finally { + registry.setCurrentObservationScope(previous); + } + } + + private void reportScopeFailure(final String what, final RuntimeException e) { + try { + // an event rather than an error: the database operation itself did not fail. The event name stays fixed (the tracing + // handler exports it as the span event name); the exception goes on the span as a high-cardinality key-value. + observation.event(Observation.Event.of("mongodb.span.scope." + what + ".failed")); + observation.highCardinalityKeyValue("mongodb.span.scope.failure", e.toString()); + } catch (RuntimeException eventFailure) { + // handlers are notified of events without protection too; the log line below still carries the failure + LOGGER.trace("Ignoring a failure while recording the span scope failure on the span", eventFailure); + } + String traceParent = context().traceParent(); + String span = traceParent == null ? "" : traceParent; + String message = what.equals("open") + ? "Failed to open the span scope; work in it is not correlated with span " + span + + ". Recorded as an event on the span." + : "Failed to close the span scope; the thread's tracing context may remain on span " + span + + " until an enclosing scope closes. Recorded as an event on the span."; + LOGGER.warn(message, e); } @Override diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeGuardTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeGuardTest.java new file mode 100644 index 0000000000..0789dfb8ef --- /dev/null +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeGuardTest.java @@ -0,0 +1,210 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.observability.micrometer; + +import com.mongodb.observability.micrometer.MongodbObservation; +import com.mongodb.observability.micrometer.MongodbObservationContext; +import io.micrometer.observation.Observation; +import io.micrometer.observation.ObservationHandler; +import io.micrometer.observation.ObservationRegistry; +import io.micrometer.tracing.handler.DefaultTracingObservationHandler; +import io.micrometer.tracing.test.simple.SimpleSpan; +import io.micrometer.tracing.test.simple.SimpleTracer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Verifies that {@link MicrometerTracer.MicrometerSpan#openScope()} isolates the thread's current observation and tracing + * span from an application {@link ObservationHandler} that throws from {@code onScopeOpened} or {@code onScopeClosed}. + * The throwing handler is registered after the tracing handler, so the tracing handler has already acted when it throws. + */ +class MicrometerSpanScopeGuardTest { + private final SimpleTracer simpleTracer = new SimpleTracer(); + private final ObservationRegistry registry = ObservationRegistry.create(); + private final ThrowingHandler throwingHandler = new ThrowingHandler(); + private final MicrometerTracer tracer = new MicrometerTracer(registry, false, 1000, null); + + @BeforeEach + void setUp() { + registry.observationConfig() + .observationHandler(new DefaultTracingObservationHandler(simpleTracer)) + .observationHandler(throwingHandler); + } + + @AfterEach + void tearDown() { + assertNull(registry.getCurrentObservation(), "a test left an observation current"); + assertNull(simpleTracer.currentSpan(), "a test left a tracing span current"); + } + + @Test + void openFailureRestoresThePreviousScopeAndReturnsNoOp() { + Observation outer = Observation.start("outer", registry); + try (Observation.Scope ignored = outer.openScope()) { + SimpleSpan outerTracingSpan = simpleTracer.currentSpan(); + assertNotNull(outerTracingSpan); + Span span = tracer.nextSpan(MongodbObservation.MONGODB_OPERATION, "insert", null, null); + throwingHandler.onOpen = () -> new RuntimeException("thrown from onScopeOpened"); + + SpanScope scope = assertDoesNotThrow(span::openScope); + + assertSame(outer, registry.getCurrentObservation()); + assertSame(outerTracingSpan, simpleTracer.currentSpan()); + assertDoesNotThrow(scope::close); + assertSame(outer, registry.getCurrentObservation()); + assertSame(outerTracingSpan, simpleTracer.currentSpan()); + assertEquals(1, throwingHandler.events.size()); + assertEquals("mongodb.span.scope.open.failed", throwingHandler.events.get(0).getName()); + // the exception text must not become the exported event name; it is attached to the span as a key-value instead + assertEquals("mongodb.span.scope.open.failed", throwingHandler.events.get(0).getContextualName()); + MongodbObservationContext context = span.getMongodbObservationContext(); + assertNotNull(context); + assertTrue(context.getHighCardinalityKeyValues().stream().anyMatch(kv -> kv.getKey().equals("mongodb.span.scope.failure") + && kv.getValue().equals("java.lang.RuntimeException: thrown from onScopeOpened")), + "the span must carry the failure reason, got " + context.getHighCardinalityKeyValues()); + span.end(); + } finally { + outer.stop(); + } + } + + @Test + void closeFailureRestoresThePreviousScope() { + Observation outer = Observation.start("outer", registry); + try (Observation.Scope outerScope = outer.openScope()) { + Span span = tracer.nextSpan(MongodbObservation.MONGODB_OPERATION, "insert", null, null); + throwingHandler.onClose = () -> new RuntimeException("thrown from onScopeClosed"); + + SpanScope scope = span.openScope(); + assertNotNull(registry.getCurrentObservation()); + assertTrue(registry.getCurrentObservation().getContext() instanceof MongodbObservationContext); + assertDoesNotThrow(scope::close); + + assertSame(outerScope, registry.getCurrentObservationScope()); + assertEquals(1, throwingHandler.events.size()); + assertEquals("mongodb.span.scope.close.failed", throwingHandler.events.get(0).getName()); + throwingHandler.onClose = null; + span.end(); + } finally { + outer.stop(); + } + } + + @Test + void runInScopeStillRunsTheActionWhenOpenFails() { + Span span = tracer.nextSpan(MongodbObservation.MONGODB_OPERATION, "insert", null, null); + throwingHandler.onOpen = () -> new RuntimeException("thrown from onScopeOpened"); + AtomicInteger runs = new AtomicInteger(); + + Span.runInScope(span, runs::incrementAndGet); + + assertEquals(1, runs.get()); + assertNull(registry.getCurrentObservation()); + assertNull(simpleTracer.currentSpan()); + span.end(); + } + + @Test + void handlerRethrowingTheSameExceptionFromCleanupAndEventDoesNotEscape() { + Span span = tracer.nextSpan(MongodbObservation.MONGODB_OPERATION, "insert", null, null); + RuntimeException preallocated = new RuntimeException("preallocated"); + throwingHandler.onOpen = () -> preallocated; + throwingHandler.onClose = () -> preallocated; + throwingHandler.onEventThrow = () -> preallocated; + + assertDoesNotThrow(() -> span.openScope().close()); + + assertEquals(0, preallocated.getSuppressed().length, "the guard must not mutate the handler's exception"); + assertNull(registry.getCurrentObservation()); + throwingHandler.onOpen = null; + throwingHandler.onClose = null; + throwingHandler.onEventThrow = null; + span.end(); + // the throwing handler is notified before the tracing handler on close, so the tracing handler never undid its scope: + // the documented residual. Reset the tracing thread-local for the teardown check. + simpleTracer.currentTraceContext().newScope(null).close(); + } + + @Test + void errorsFromHandlersPropagate() { + Span span = tracer.nextSpan(MongodbObservation.MONGODB_OPERATION, "insert", null, null); + throwingHandler.onOpen = () -> new AssertionError("thrown from onScopeOpened"); + try { + assertThrows(AssertionError.class, span::openScope); + } finally { + // the guard deliberately does not handle Errors, so undo the partially opened scope here + throwingHandler.onOpen = null; + Observation.Scope leaked = registry.getCurrentObservationScope(); + assertNotNull(leaked, "the Error escaped before Micrometer could restore the scope"); + leaked.close(); + span.end(); + } + } + + private static final class ThrowingHandler implements ObservationHandler { + private volatile Supplier onOpen; + private volatile Supplier onClose; + private volatile Supplier onEventThrow; + private final List events = new CopyOnWriteArrayList<>(); + + @Override + public boolean supportsContext(final Observation.Context context) { + return context instanceof MongodbObservationContext; + } + + @Override + public void onScopeOpened(final Observation.Context context) { + throwIfSet(onOpen); + } + + @Override + public void onScopeClosed(final Observation.Context context) { + throwIfSet(onClose); + } + + @Override + public void onEvent(final Observation.Event event, final Observation.Context context) { + events.add(event); + throwIfSet(onEventThrow); + } + + private static void throwIfSet(final Supplier supplier) { + if (supplier == null) { + return; + } + Throwable t = supplier.get(); + if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } + throw (Error) t; + } + } +} diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java index bd52c01057..a242e920fa 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java @@ -32,12 +32,17 @@ import com.mongodb.observability.ObservabilitySettings; import com.mongodb.client.observability.SpanTree; import com.mongodb.client.observability.SpanTree.SpanNode; +import com.mongodb.event.ConnectionCheckedInEvent; +import com.mongodb.event.ConnectionCheckedOutEvent; +import com.mongodb.event.ConnectionCreatedEvent; +import com.mongodb.internal.connection.TestConnectionPoolListener; import com.mongodb.connection.ClusterConnectionMode; import com.mongodb.connection.ClusterSettings; import com.mongodb.observability.micrometer.MicrometerObservabilitySettings; import io.micrometer.common.KeyValues; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationConvention; +import io.micrometer.observation.ObservationHandler; import io.micrometer.observation.ObservationRegistry; import io.micrometer.tracing.exporter.FinishedSpan; import io.micrometer.tracing.test.reporter.inmemory.InMemoryOtelSetup; @@ -61,6 +66,8 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import static com.mongodb.ClusterFixture.getCredential; @@ -626,6 +633,61 @@ void testBackgroundLogMessagesAreNotAttributedToAnOperation() throws Interrupted // Tests 14 and 15 apply only to driver-managed log output and are not applicable to Java: the driver logs through SLF4J and // has no driver-managed log destinations. The reactive subclass runs Tests 10 to 13 as the asynchronous API. + /** + * Not a numbered spec prose test: an application {@link ObservationHandler} that throws from {@code onScopeOpened} + * while the "Connection checked in" message is emitted must not abort {@code PooledConnection.close()}. Micrometer + * switches the thread's current scope before notifying handlers and does not protect the notification, so without the + * driver's guard the check-in is skipped and the connection leaks. With a single-connection pool, a leak makes the + * second operation time out waiting for a connection. + */ + @DisplayName("A throwing observation handler at connection check-in does not leak the connection") + @Test + void testThrowingObservationHandlerAtConnectionCheckedInDoesNotLeakTheConnection() throws InterruptedException, TimeoutException { + String appName = "otel-log-throwing-handler-checkin"; + AtomicInteger thrown = new AtomicInteger(); + observationRegistry.observationConfig().observationHandler(new ObservationHandler() { + @Override + public boolean supportsContext(final Observation.Context context) { + // the check-in message is emitted in the scope of the operation span + return context instanceof MongodbObservationContext + && ((MongodbObservationContext) context).getObservationType() == MongodbObservation.MONGODB_OPERATION; + } + + @Override + public void onScopeOpened(final Observation.Context context) { + // the scope is opened from Span.runInScope <- PooledConnection.connectionCheckedIn, before the pool listener runs + for (StackTraceElement element : Thread.currentThread().getStackTrace()) { + if (element.getMethodName().equals("connectionCheckedIn")) { + thrown.incrementAndGet(); + throw new RuntimeException("thrown from onScopeOpened at connection check-in"); + } + } + } + }); + TestConnectionPoolListener poolListener = new TestConnectionPoolListener(asList("connectionCreatedEvent", + "connectionCheckedOutEvent", "connectionCheckedInEvent")); + MongoClientSettings settings = MongoClientSettings.builder(tracedSettings(appName)) + .applyToConnectionPoolSettings(b -> b + .maxSize(1) + .maxWaitTime(5, TimeUnit.SECONDS) + .addConnectionPoolListener(poolListener)) + .build(); + // the interceptor force-enables structured logging, so the check-in message (and its scope opening) is emitted + try (SpanRecordingInterceptor ignored = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); + MongoClient client = createMongoClient(settings)) { + MongoCollection collection = client.getDatabase(getDefaultDatabaseName()).getCollection("test"); + collection.insertOne(new Document("x", 1)); + collection.insertOne(new Document("x", 2)); + + poolListener.waitForEvent(ConnectionCheckedInEvent.class, 2, 5, TimeUnit.SECONDS); + assertTrue(thrown.get() >= 2, "the handler must have thrown at each check-in, threw " + thrown.get()); + assertEquals(2, poolListener.countEvents(ConnectionCheckedOutEvent.class), "each operation must check a connection out"); + assertEquals(2, poolListener.countEvents(ConnectionCheckedInEvent.class), "every connection must be checked back in"); + assertEquals(1, poolListener.countEvents(ConnectionCreatedEvent.class), "one connection must be created and reused"); + assertNoSpanIsCurrent(); + } + } + /** * Runs {@code body} in a transaction on {@code session}, as the spec's {@code withTransaction} step requires. */