Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
1ddb17a
JAVA-5734 Emit command events inside the command span scope (sync and…
nhachicha Nov 12, 2026
e1c6e75
JAVA-5734 Allow MicrometerSpan scopes to nest
nhachicha Nov 12, 2026
0ada3b6
JAVA-5734 Track MicrometerSpan scopes per thread
nhachicha Nov 12, 2026
45a0405
JAVA-5734 Add SpanScopes.runInScope helper
nhachicha Nov 12, 2026
3f5ce4c
JAVA-5734 Emit server selection log messages inside the operation spa…
nhachicha Nov 12, 2026
ab63bfb
JAVA-5734 Fix checkstyle violations in SpanScopesTest
nhachicha Nov 12, 2026
cab737f
JAVA-5734 Emit connection checkout log messages inside the operation …
nhachicha Nov 12, 2026
fa2180d
JAVA-5734 Only open the operation span scope when connection logging …
nhachicha Nov 12, 2026
7d7e1fb
JAVA-5734 Add OpenTelemetry prose tests 10-13 and 15 for log/trace co…
nhachicha Nov 12, 2026
20bcaf2
JAVA-5734 Strengthen trace assertions in prose tests 10 and 12
nhachicha Nov 12, 2026
c0cd96c
JAVA-5734 Address final review: clear per-thread scope state and fix …
nhachicha Nov 12, 2026
0bb84f8
JAVA-5734 Assert no span remains current after traced operations
nhachicha Nov 12, 2026
d68b0a7
JAVA-5734 Document and test the TransactionSpan cross-thread scope be…
nhachicha Nov 15, 2026
4c322d0
JAVA-5734 Assert the transaction span ends when finalized on another …
nhachicha Nov 15, 2026
f46c1c1
JAVA-5734 Do not hold the transaction span scope across user calls
nhachicha Nov 15, 2026
feeee2d
JAVA-5734 Update log correlation prose tests to specifications PR 200…
nhachicha Nov 16, 2026
3f65e68
JAVA-5734 Explain why MicrometerSpan keeps a per-thread scope stack
nhachicha Nov 25, 2026
f43f527
JAVA-5734 Clarify that every openScope must be matched by a closeScope
nhachicha Nov 25, 2026
519aab5
JAVA-5734 Move runInScope onto the Span interface
nhachicha Nov 25, 2026
8861ba7
JAVA-5734 Simplify TracingScopedCommandEventSender javadoc
nhachicha Nov 25, 2026
e5d55f5
JAVA-5734 Simplify TransactionSpan javadoc
nhachicha Nov 25, 2026
f5b6a98
JAVA-5734 Use assertTrue with a clear message in the log scope tests
nhachicha Nov 25, 2026
f4c087e
JAVA-5734 Document the purpose of BaseClusterLogScopeTest
nhachicha Nov 25, 2026
8a3d726
JAVA-5734 Document the purpose of DefaultConnectionPoolLogScopeTest
nhachicha Nov 25, 2026
409ce09
JAVA-5734 Assert the first checkout's span is not re-entered on conne…
nhachicha Nov 25, 2026
6031835
JAVA-5734 Document the goal of MicrometerSpanScopeTest
nhachicha Nov 25, 2026
4c4bcd4
JAVA-5734 Document the goal of SpanRunInScopeTest
nhachicha Nov 25, 2026
c72401e
JAVA-5734 Remove redundant comments
nhachicha Nov 25, 2026
cb3dafa
JAVA-5734 Remove stray blank line
nhachicha Nov 25, 2026
f104583
JAVA-5734 Consolidate scope unit tests to the essentials
nhachicha Nov 25, 2026
77615b2
JAVA-5734 Drop volatile from PooledConnection.operationSpan to match …
nhachicha Nov 25, 2026
14975e4
JAVA-5734 Return a closeable handle from Span.openScope and drop the …
nhachicha Nov 26, 2026
9bc5ebd
JAVA-5734 Keep only the prose tests for log/trace correlation
nhachicha Nov 26, 2026
c32d58e
JAVA-5734 Drop the dead SRV assumption from the failing-selection pro…
nhachicha Nov 26, 2026
9e4a889
JAVA-5734 Simplify the log/trace correlation prose tests
nhachicha Nov 26, 2026
37b34a5
JAVA-5734 Isolate span scope handling from throwing ObservationHandlers
nhachicha Dec 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions driver-core/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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") }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.Span;
import com.mongodb.internal.selector.AtMostTwoRandomServerSelector;
import com.mongodb.internal.selector.LatencyMinimizingServerSelector;
import com.mongodb.internal.selector.MinimumOperationCountServerSelector;
Expand Down Expand Up @@ -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: {}");
Span.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()),
Expand All @@ -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: {}.");
Span.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage));
}
}

private static void logServerSelectionFailed(
static void logServerSelectionFailed(
final OperationContext operationContext,
final ClusterId clusterId,
final MongoException failure,
Expand All @@ -602,15 +605,16 @@ 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()),
new Entry(OPERATION_ID, operationContext.getId()),
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: {}");
Span.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage));
}
}

Expand All @@ -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()),
Expand All @@ -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: {}");
Span.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
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.thread.DaemonThreadFactory;
import com.mongodb.internal.time.StartTime;
import com.mongodb.internal.time.Timeout;
Expand Down Expand Up @@ -273,11 +274,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<LogMessage.Entry> entries = createBasicEntries();
final List<LogMessage.Entry> 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);
Span.runInScope(operationContext.getTracingSpan(),
() -> logMessage("Connection checkout failed", clusterId, message, entries));
}
connectionPoolListener.connectionCheckOutFailed(
new ConnectionCheckOutFailedEvent(serverId, operationContext.getId(), reason, checkoutDuration.toNanos()));
Expand Down Expand Up @@ -565,11 +567,12 @@ private void connectionCheckedOut(
ConnectionId connectionId = getId(connection);
ClusterId clusterId = serverId.getClusterId();
if (requiresLogging(clusterId)) {
List<LogMessage.Entry> entries = createBasicEntries();
final List<LogMessage.Entry> 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);
Span.runInScope(operationContext.getTracingSpan(),
() -> logMessage("Connection checked out", clusterId,
"Connection checked out: address={}:{}, driver-generated ID={}, duration={} ms", entries));
}

connectionPoolListener.connectionCheckedOut(
Expand All @@ -585,7 +588,10 @@ private void connectionCheckedOut(
*/
private StartTime connectionCheckoutStarted(final OperationContext operationContext) {
StartTime checkoutStart = StartTime.now();
logEventMessage("Connection checkout started", "Checkout started for connection to {}:{}");
if (requiresLogging(serverId.getClusterId())) {
Span.runInScope(operationContext.getTracingSpan(),
() -> logEventMessage("Connection checkout started", "Checkout started for connection to {}:{}"));
}

connectionPoolListener.connectionCheckOutStarted(new ConnectionCheckOutStartedEvent(serverId, operationContext.getId()));
return checkoutStart;
Expand Down Expand Up @@ -615,6 +621,8 @@ private class PooledConnection implements InternalConnection {
private final AtomicBoolean isClosed = new AtomicBoolean();
private Connection.PinningMode pinningMode;
private long operationId;
@Nullable
private Span operationSpan;

PooledConnection(final UsageTrackingInternalConnection wrapped) {
this.wrapped = notNull("wrapped", wrapped);
Expand All @@ -630,6 +638,7 @@ public int getGeneration() {
*/
public void checkedOutForOperation(final OperationContext operationContext) {
this.operationId = operationContext.getId();
this.operationSpan = operationContext.getTracingSpan();
}

@Override
Expand Down Expand Up @@ -677,9 +686,11 @@ public void close() {

private void connectionCheckedIn() {
ConnectionId connectionId = getId(wrapped);
logEventMessage("Connection checked in",
"Connection checked in: address={}:{}, driver-generated ID={}",
connectionId.getLocalValue());
if (requiresLogging(serverId.getClusterId())) {
Span.runInScope(operationSpan, () -> logEventMessage("Connection checked in",
"Connection checked in: address={}:{}, driver-generated ID={}",
connectionId.getLocalValue()));
}
connectionPoolListener.connectionCheckedIn(new ConnectionCheckedInEvent(connectionId, operationId));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -452,6 +453,7 @@ private <T> 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()
Expand All @@ -471,36 +473,40 @@ private <T> 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) {
tracingScope = tracingSpan.openScope();
}
if (isLoggingCommandNeeded) {
commandEventSender = new LoggingCommandEventSender(
SECURITY_SENSITIVE_COMMANDS, SECURITY_SENSITIVE_HELLO_COMMANDS, description, commandListener,
operationContext, message, commandDocument,
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();
try {
commandEventSender.sendFailedEvent(t);
} finally {
if (tracingSpan != null) {
tracingSpan.error(t);
tracingScope.close();
tracingSpan.end();
}
}
commandEventSender.sendFailedEvent(t);
throw t;
}

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;
Expand All @@ -522,7 +528,7 @@ public <T> void send(final CommandMessage message, final Decoder<T> decoder, fin
@Override
public <T> T receive(final Decoder<T> 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
Expand Down Expand Up @@ -568,13 +574,13 @@ private void trySendMessage(final CommandMessage message, final ByteBufferBsonOu
}

private <T> T receiveCommandMessageResponse(final Decoder<T> 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();
}
}
Expand Down Expand Up @@ -732,6 +738,9 @@ private <T> void sendAndReceiveAsyncInternal(final CommandMessage message, final
if (isTracingCommandPayloadNeeded) {
tracingSpan.setQueryText(commandDocument);
}
if (tracingSpan != null && isLoggingCommandNeeded) {
commandEventSender = new TracingScopedCommandEventSender(commandEventSender, tracingSpan);
}

final Span commandSpan = tracingSpan;
SingleResultCallback<T> tracingCallback = commandSpan == null ? callback : (result, t) -> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* 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;
import com.mongodb.internal.observability.micrometer.SpanScope;

/**
* 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.
*
* <p>This class is not part of the public API and may be removed or changed at any time</p>
*/
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() {
try (SpanScope ignored = span.openScope()) {
delegate.sendStartedEvent();
}
}

@Override
public void sendFailedEvent(final Throwable t) {
try (SpanScope ignored = span.openScope()) {
delegate.sendFailedEvent(t);
}
}

@Override
public void sendSucceededEvent(final ResponseBuffers responseBuffers) {
try (SpanScope ignored = span.openScope()) {
delegate.sendSucceededEvent(responseBuffers);
}
}

@Override
public void sendSucceededEventForOneWayCommand() {
try (SpanScope ignored = span.openScope()) {
delegate.sendSucceededEventForOneWayCommand();
}
}
}
Loading