Skip to content

JAVA-6282 getMore span nesting for OpenTelemetry tracing - #2116

Draft
nhachicha wants to merge 37 commits into
mongodb:mainfrom
nhachicha:JAVA-6282
Draft

nhachicha wants to merge 37 commits into
mongodb:mainfrom
nhachicha:JAVA-6282

Conversation

@nhachicha

@nhachicha nhachicha commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

JAVA-6282 (DRIVERS-3598), following the Rust reference implementation mongodb/mongo-rust-driver#1804.

Stacked on #2099. Only the JAVA-6282 commits belong to this PR: JAVA-6282 diff.

Changes

  • Each getMore sent while the caller iterates a cursor is traced under its own getMore db.coll operation span, a sibling of the cursor-creating span (parent: the transaction span, or the app's current span). Cursors drained internally (client bulkWrite) keep their getMores under the operation span.
  • db.mongodb.cursor_id is recorded on operation spans and on command spans that create a cursor with a non-zero id.
  • Operation IDs are unchanged: getMore command and pool events still report the cursor-creating operation's ID.
  • Unified test runner supports schema 1.29 ($$gte, ignoreExtraSpans at every level); the 1.28 accessToken fixtures are skipped (JAVA-6136). Adds prose Tests 3 and 4.

No public API changes. Touches com.mongodb.internal.connection (reads the reply's cursor id only when tracing).

… 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
Add the $$gte operator and apply ignoreExtraSpans at every level of the
span tree. Skip the schema 1.28 accessToken KMS provider fixtures, which
the runner does not support yet (JAVA-6136).
A getMore sent while the caller iterates a cursor is traced under a new
'getMore db.coll' operation span, parented on the transaction span the
cursor was created under or on the application's current span, instead
of under the already finished operation span that created the cursor. A
cursor the operation iterates internally (client bulkWrite) keeps its
getMore commands under the operation span.

Record db.mongodb.cursor_id on operation spans, and on the command span
of a command that returns a non-zero cursor id.

Adds prose Tests 3 and 4 for sync and reactive.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved defects mislabel listCollections getMore spans, associate pinned-connection check-ins with stale spans, and reject valid $$gte expectations and extra spans that should be ignored.

4 open issues
What changed in this PR

Gives caller-driven getMore commands their own operation spans in the Java driver, building on #2099’s tracing-context propagation.

Changes:

  • Separates caller-driven cursor tracing from internal bulk-write iteration and records cursor IDs.
  • Updates span scopes and log correlation across synchronous and asynchronous paths.
  • Adds tracing tests and unified test schema 1.29 support.
File Description
gradle/​libs.versions.toml Registers Micrometer observation test dependency.
driver-sync/​src/​test/​functional/​com/​mongodb/​client/​unified/​ValueMatcher.java Adds $$gte matching.
driver-sync/​src/​test/​functional/​com/​mongodb/​client/​unified/​UnifiedTestModifications.java Skips unsupported access-token fixtures.
driver-sync/​src/​test/​functional/​com/​mongodb/​client/​unified/​UnifiedTest.java Enables schema 1.29.
driver-sync/​src/​test/​functional/​com/​mongodb/​client/​observability/​SpanTree.java Filters extra spans recursively.
driver-sync/​src/​test/​functional/​com/​mongodb/​client/​AbstractMicrometerProseTest.java Adds cursor and log-correlation tests.
driver-sync/​src/​main/​com/​mongodb/​client/​internal/​MongoClusterImpl.java Explicitly closes operation scopes.
driver-sync/​src/​main/​com/​mongodb/​client/​internal/​ClientSessionImpl.java Removes transaction-wide scope opening.
driver-reactive-streams/​src/​test/​functional/​com/​mongodb/​reactivestreams/​client/​observability/​MicrometerProseTest.java Adapts transaction tests for reactive execution.
driver-core/​src/​test/​unit/​com/​mongodb/​observability/​micrometer/​DefaultMongodbObservationConventionTest.java Tests operation cursor-ID attributes.
driver-core/​src/​test/​unit/​com/​mongodb/​internal/​observability/​micrometer/​MicrometerTracerRecordingTest.java Updates scope lifecycle tests.
driver-core/​src/​test/​unit/​com/​mongodb/​internal/​observability/​micrometer/​MicrometerTraceParentTest.java Adapts trace-parent tests to scope handles.
driver-core/​src/​test/​unit/​com/​mongodb/​internal/​connection/​InternalStreamConnectionTracingTest.java Updates recording-span scope tracking.
driver-core/​src/​main/​com/​mongodb/​observability/​micrometer/​DefaultMongodbObservationConvention.java Emits operation cursor-ID attributes.
driver-core/​src/​main/​com/​mongodb/​internal/​operation/​SyncOperationHelper.java Passes internal-iteration flag to cursors.
driver-core/​src/​main/​com/​mongodb/​internal/​operation/​CommandCursor.java Creates synchronous getMore operation spans.
driver-core/​src/​main/​com/​mongodb/​internal/​operation/​ClientBulkWriteOperation.java Marks internally drained cursors.
driver-core/​src/​main/​com/​mongodb/​internal/​operation/​AsyncOperationHelper.java Passes asynchronous internal-iteration flag.
driver-core/​src/​main/​com/​mongodb/​internal/​operation/​AsyncCommandCursor.java Creates asynchronous getMore operation spans.
driver-core/​src/​main/​com/​mongodb/​internal/​observability/​micrometer/​TransactionSpan.java Removes transaction scope management.
driver-core/​src/​main/​com/​mongodb/​internal/​observability/​micrometer/​TracingManager.java Creates cursor spans and records cursor IDs.
driver-core/​src/​main/​com/​mongodb/​internal/​observability/​micrometer/​SpanScope.java Introduces closeable scope handles.
driver-core/​src/​main/​com/​mongodb/​internal/​observability/​micrometer/​Span.java Adds scoped execution support.
driver-core/​src/​main/​com/​mongodb/​internal/​observability/​micrometer/​MicrometerTracer.java Returns independent scope handles.
driver-core/​src/​main/​com/​mongodb/​internal/​connection/​TracingScopedCommandEventSender.java Scopes asynchronous command events.
driver-core/​src/​main/​com/​mongodb/​internal/​connection/​ProtocolHelper.java Extracts response cursor IDs.
driver-core/​src/​main/​com/​mongodb/​internal/​connection/​OperationContext.java Preserves transaction-span context.
driver-core/​src/​main/​com/​mongodb/​internal/​connection/​InternalStreamConnection.java Scopes command events and records cursor IDs.
driver-core/​src/​main/​com/​mongodb/​internal/​connection/​DefaultConnectionPool.java Associates pool logs with operation spans.
driver-core/​src/​main/​com/​mongodb/​internal/​connection/​BaseCluster.java Scopes server-selection logs.
driver-core/​build.gradle.kts Adds observation testing dependency.

Review effort: Balanced

*/
public void checkedOutForOperation(final OperationContext operationContext) {
this.operationId = operationContext.getId();
this.operationSpan = operationContext.getTracingSpan();
Comment on lines +304 to +305
Span span = assertNotNull(createOperationSpan(cursorOperationContext.getTransactionSpan(), operationContext, "getMore",
namespace));
Comment on lines +175 to +177
reportedSpans.removeIf(node ->
expectedSpans.stream().noneMatch(expectedNode -> expectedNode.getName().equalsIgnoreCase(node.getName()))
);
value = value.asDocument().getNumber("$$lte");
assertTrue(actualValue.asNumber().longValue() <= value.asNumber().longValue());
return;
case "$$gte":
@stIncMale

stIncMale commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

@nhachicha I don't know any details, so we should discuss this at a catchup, but the title "Give each caller-driven getMore its own operation span" looks suspicious to me:

  • An operation is identified by CommandEvent.getOperationId, and all getMore commands on a cursor have the same operation ID as the command that created the cursor. Even when we automatically resume iteration in ChangeStreamBatchCursor after an exception, the original operation ID is preserved.
  • The tracing functionality should not use the term "operation" in a different sense. If we indeed need different spans for separate commands, then those could be called command spans, or something else, but not operation spans.

Update:
Discussed at a catchup meeting. Summary (in my own words, hopefully I express the idea correctly, even if I don't use the correct terms from the spec, as I haven't read it):

  1. Having a tracing operation span that starts and ends when the corresponding operation starts and ends is not useful when operation spans of different operations could exist concurrently within the same execution thread. This may happen for any operation that involves a cursor: one operation creates a cursor, then another operation is executed, then the cursor is iterated.
  2. So the operation span for such operations is split into multiple same-level spans, which we still call operation spans. The command creating the cursor, and each subsequent getMore command has the corresponding command span, as usual, and it is wrapped into its own operation span. But such operation spans all exist to trace the same operation, have its operation ID, and can later be used to aggregate info about this operation.

It looks like this (the concrete operation and request IDs are given just to illustrate which ones match):

find operation span {
    operation ID: 1
    find command span {
        request ID: 35
    }
}

... spans for other operations (different operation ID) may be opened and closed here

synthetic operation span {
    operation ID: 1
    getMore command span {
        request ID: 36
    }
}

... spans for other operations (different operation ID) may be opened and closed here

synthetic operation span {
    operation ID: 1
    getMore command span {
        request ID: 37
    }
}

All the three spans above are there to trace the same find operation with ID 1.

@nhachicha nhachicha changed the title JAVA-6282 Give each caller-driven getMore its own operation span JAVA-6282 getMore span nesting for OpenTelemetry tracing Dec 3, 2026

This branch has not been deployed

No deployments
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.

3 participants