Skip to content

JAVA-5734 OpenTelemetry Context Propagation in Logs - #2099

Merged
nhachicha merged 36 commits into
mongodb:mainfrom
nhachicha:JAVA-5734
Dec 4, 2026
Merged

nhachicha merged 36 commits into
mongodb:mainfrom
nhachicha:JAVA-5734

Conversation

@nhachicha

@nhachicha nhachicha commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

JAVA-5734 reference implementation of mongodb/specifications#2008 (DRIVERS-3739). Covered log messages are emitted while their covering span is the current Micrometer observation, so SLF4J MDC bridges attach the right trace/span ids. No trace fields are added to messages (the driver logs through a framework).

  • Command events fire inside the command span scope (sync and async).
  • Server selection and connection checkout messages are emitted inside the operation span scope.
  • Prose tests 10–13 added to AbstractMicrometerProseTest (sync and reactive). Tests 14 and 15 do not apply to Java.

No public API changes. Changes in com.mongodb.internal.connection

Evergreen patch: https://spruce.corp.mongodb.com/version/6b085208ab7c0b0007b82e79/tasks?sorts=STATUS%3AASC%3BBASE_STATUS%3ADESC

@nhachicha nhachicha changed the title JAVA-5734 Emit log messages inside the covering span scope for log/trace correlation JAVA-5734 OpenTelemetry Context Propagation in Logs Nov 16, 2026
@nhachicha nhachicha self-assigned this Nov 25, 2026
… 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.
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.
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.
…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.
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.
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.
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.
…per-thread scope stack

Span.openScope() returned void, so MicrometerSpan had to remember which
Micrometer scope to close and kept a ThreadLocal<Deque<Observation.Scope>>
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)
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).
…se 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.
- 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
@nhachicha
nhachicha requested a review from vbabanin November 26, 2026 15:50
@nhachicha
nhachicha marked this pull request as ready for review November 26, 2026 15:50
@nhachicha
nhachicha requested a review from a team as a code owner November 26, 2026 15:50
@vbabanin

vbabanin commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

While testing the log/trace correlation work, I found failure modes that I think we should address.

The root mechanism: SimpleObservation#openScope (micrometer-observation 1.17.1) switches the registry's thread-local current scope before notifying handlers, and notifies them without exception protection. If an application-installed ObservationHandler (for example, an MDC bridge) throws from onScopeOpened, openScope() fails without returning the scope handle, even though the thread's current observation has already changed. Our try-with-resources cannot close a scope it never received.

Case 1: A throwing handler leaves the reactive transport thread stuck on an ended span

TracingScopedCommandEventSender opens per-event scopes on Netty event-loop threads, where they can be the outermost scopes.

If a handler throws, the thread remains associated with the failed command's span. Subsequent commands on that thread inherit the ended span as their parent, causing incorrect trace attribution across unrelated operations because the transport thread is reused.

It was reproduced with a single-threaded event loop. After the handler throws once during the first command's succeeded event, the second command's span is incorrectly parented under the first command's ended span.

Reproducer: [testThrowingObservationHandlerDoesNotStickTransportThread](vbabanin@3fbd477)

Case 2: The same leak exists in the sync driver around the operation span, and potentially at other emission sites

MongoClusterImpl opens the operation span's scope on the calling thread.

If a handler throws during scope opening, the same failure leaves the calling thread associated with the previous operation's ended span. A subsequent operation on that thread can then inherit it as a parent.

This is the same scope-state corruption as Issue 1, but on the caller's thread rather than the transport thread in the TracingScopedCommandEventSender.

The test throws once during operation scope opening, allows the first operation to fail, and then executes a second operation. The second operation's span is incorrectly parented under the first operation's ended span.

Reproducer: testThrowingObservationHandlerDoesNotStickCurrentSpan

I have not verified the remaining scope-opening sites individually (server selection, connection checkout, and other covered messages). However, they share the same underlying Micrometer behavior, so the risk exists wherever a failing scope is the outermost scope on its thread.

Case 3: A failed check-in emission leaks connections (in DEBUG)

The "Connection checked in" message opens a scope inside PooledConnection.close().

If an application-installed handler throws during that scope opening, the exception escapes close() before the connection is returned to the pool:

  • ConnectionCheckedInEvent is never emitted.
  • pool.release(...) is never called.
  • The operation fails with the handler's exception.
  • Subsequent operations check out new connections while the previous connections remain checked out.

The test registers a handler that throws only during the check-in emission, runs two operations, and verifies that both connections are checked back in and that a single connection is created and reused.

It currently observes zero check-ins and two connections created. Repeated failures can eventually exhaust the pool and cause operations to time out.

This path is DEBUG-gated, which limits exposure in production. However, enabling DEBUG logging should not compromise connection pool invariants, even in such edge cases.

Reproducer: [testThrowingObservationHandlerAtConnectionCheckedInMustNotLeakConnection](vbabanin@3fbd477)

Parallel with our listener multicasters

We already protect driver bookkeeping from exceptions thrown by user-provided CommandListener, ConnectionPoolListener, and similar listeners. Our multicasters catch these exceptions and log a warning rather than allowing them to interrupt driver execution.

An application-installed ObservationHandler is similar user-provided instrumentation code. Micrometer does not isolate handler exceptions, but we can protect our own boundaries around openScope() and closeScope().

Suggested approach

I think we could handle all cases centrally in MicrometerSpan#openScope().

If opening a scope fails, attempt to close the partially installed scope and restore the previous thread-local state, even if cleanup throws.

Similar to our listener multicasters, we could catch the RuntimeException, record it on the span, log a warning, and return a no-op SpanScope to let execution continue safely.

For the warning, we could include the W3C traceparent available through span.context().traceParent(), helping users correlate the failure with the span in their tracing backend.

For example:
Failed to open the span scope for this log message; it will carry no trace correlation. The failure is recorded on span <traceParent>.

For example:

Failed to open the span scope for this log message; it will carry no trace correlation. The failure is recorded on span <traceParent>.

Suggested guard
{
scope = observation.openScope(); 
} catch (RuntimeException e) {
    Observation.Scope leaked = observationRegistry.getCurrentObservationScope();
    try {
        if (leaked != null && leaked != previous
                && leaked.getCurrentObservation() == observation) {
            leaked.close();
        }
    } catch (RuntimeException closeFailure) {
        if (closeFailure != e) {
            e.addSuppressed(closeFailure);
        }
    } finally {
        observationRegistry.setCurrentObservationScope(previous);
    }

    // Record the original exception on the observation.
    // Log a warning, potentially including the traceparent.
}

Given the potential impact on tracing and connection pool state, I think it is worth adding the guard in this PR. What do you think?

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.
@nhachicha
nhachicha merged commit 62928cd into mongodb:main Dec 4, 2026
61 checks passed
@nhachicha
nhachicha deleted the JAVA-5734 branch December 4, 2026 12:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants