From 91e05b9c1ba579b54b62338678e8309fcfe1dec4 Mon Sep 17 00:00:00 2001 From: Jin Seop Kim Date: Mon, 16 Nov 2026 11:09:18 -0500 Subject: [PATCH 1/7] feat(gax): implement inScope() in OpenTelemetryTracingTracer --- .../tracing/OpenTelemetryTracingTracer.java | 32 ++++++- .../OpenTelemetryTracingTracerTest.java | 88 +++++++++++++++++++ 2 files changed, 117 insertions(+), 3 deletions(-) diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java index cd95610d7cab..37936798f4ed 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java @@ -61,14 +61,40 @@ class OpenTelemetryTracingTracer implements ApiTracer { private final Context parentContext; // Trace context containing the operationSpan, serving as the parent for attempt spans. private final Context operationContext; - private @Nullable Span operationSpan; - private @Nullable Span attemptSpan; + private volatile @Nullable Span operationSpan; + private volatile @Nullable Span attemptSpan; + + /** + * Returns the active attempt span when an attempt is in-flight, falling back to the overall + * operation span when between attempts or at operation completion. + * + * @return the current {@link Span}, or {@code null} if the operation has ended + */ + private @Nullable Span getCurrentSpan() { + Span currentSpan = attemptSpan; + return currentSpan != null ? currentSpan : operationSpan; + } + + /** + * Activates the current span on the calling thread's OpenTelemetry {@link Context}. + * + * @return a {@link Scope} that restores the previous context when closed + */ + @Override + public Scope inScope() { + Span currentSpan = getCurrentSpan(); + if (currentSpan == null) { + return () -> {}; + } + io.opentelemetry.context.Scope otelScope = currentSpan.makeCurrent(); + return otelScope::close; + } @Override public void injectTraceContext(Map carrier) { // Prefer the active attempt span so outgoing RPC wire context reflects the specific attempt; // fall back to the overall operation span if no attempt is currently in-flight. - Span currentSpan = attemptSpan != null ? attemptSpan : operationSpan; + Span currentSpan = getCurrentSpan(); if (currentSpan != null) { Context context = Context.current().with(currentSpan); W3CTraceContextPropagator.getInstance() diff --git a/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpenTelemetryTracingTracerTest.java b/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpenTelemetryTracingTracerTest.java index 3c647c3b8dc4..9abe5e91c2e1 100644 --- a/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpenTelemetryTracingTracerTest.java +++ b/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpenTelemetryTracingTracerTest.java @@ -49,12 +49,18 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanBuilder; +import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.api.trace.Tracer; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -783,4 +789,86 @@ void testOperationSpanName_replacesSlashWithDotInFullMethodName() { verify(tracer) .spanBuilder("google.cloud.secretmanager.v1.SecretManagerService.AccessSecretVersion"); } + + @Test + void testInScope_withAttemptSpan_activatesAttemptSpanAndFallsBackToOperationSpan() { + SpanContext opContext = + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000010", + TraceFlags.getSampled(), + TraceState.getDefault()); + SpanContext attemptContext = + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000020", + TraceFlags.getSampled(), + TraceState.getDefault()); + Span realOpSpan = Span.wrap(opContext); + Span realAttemptSpan = Span.wrap(attemptContext); + when(operationSpanBuilder.startSpan()).thenReturn(realOpSpan); + when(spanBuilder.startSpan()).thenReturn(realAttemptSpan); + + openTelemetryTracingTracer = + new OpenTelemetryTracingTracer(tracer, ApiTracerContext.empty(), ATTEMPT_SPAN_NAME); + openTelemetryTracingTracer.attemptStarted(new Object(), 0); + + assertThat(Span.current().getSpanContext().isValid()).isFalse(); + + // While attempt is active, inScope() activates attemptSpan + try (ApiTracer.Scope ignored = openTelemetryTracingTracer.inScope()) { + assertThat(Span.current()).isEqualTo(realAttemptSpan); + assertThat(Span.current().getSpanContext().getSpanId()).isEqualTo("0000000000000020"); + } + assertThat(Span.current().getSpanContext().isValid()).isFalse(); + + // After attempt ends, inScope() falls back to operationSpan + openTelemetryTracingTracer.attemptSucceeded(); + try (ApiTracer.Scope ignored = openTelemetryTracingTracer.inScope()) { + assertThat(Span.current()).isEqualTo(realOpSpan); + assertThat(Span.current().getSpanContext().getSpanId()).isEqualTo("0000000000000010"); + } + assertThat(Span.current().getSpanContext().isValid()).isFalse(); + + // After operation ends, inScope() is a no-op + openTelemetryTracingTracer.operationSucceeded(); + try (ApiTracer.Scope ignored = openTelemetryTracingTracer.inScope()) { + assertThat(Span.current().getSpanContext().isValid()).isFalse(); + } + } + + @Test + void testInScope_multithreadedExecution_noLeakAcrossThreads() throws Exception { + SpanContext attemptContext = + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getSampled(), + TraceState.getDefault()); + Span realAttemptSpan = Span.wrap(attemptContext); + when(spanBuilder.startSpan()).thenReturn(realAttemptSpan); + + openTelemetryTracingTracer = + new OpenTelemetryTracingTracer(tracer, ApiTracerContext.empty(), ATTEMPT_SPAN_NAME); + + openTelemetryTracingTracer.attemptStarted(new Object(), 0); + assertThat(Span.current().getSpanContext().isValid()).isFalse(); + + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + executor + .submit( + () -> { + try (ApiTracer.Scope ignored = openTelemetryTracingTracer.inScope()) { + assertThat(Span.current()).isEqualTo(realAttemptSpan); + } + assertThat(Span.current().getSpanContext().isValid()).isFalse(); + }) + .get(5, TimeUnit.SECONDS); + } finally { + executor.shutdownNow(); + } + + assertThat(Span.current().getSpanContext().isValid()).isFalse(); + } } From 5401f3f49c42ec9a420ec88ae93e7f9a5bc36505 Mon Sep 17 00:00:00 2001 From: Jin Seop Kim Date: Mon, 16 Nov 2026 11:38:48 -0500 Subject: [PATCH 2/7] fix(gax): suppress MustBeClosedChecker on indirectly closed OTel scope --- .../com/google/api/gax/tracing/OpenTelemetryTracingTracer.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java index 37936798f4ed..86c2efad5a53 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java @@ -86,6 +86,9 @@ public Scope inScope() { if (currentSpan == null) { return () -> {}; } + // Suppressing MustBeClosedChecker because the scope is closed indirectly via the returned + // Scope. + @SuppressWarnings("MustBeClosedChecker") io.opentelemetry.context.Scope otelScope = currentSpan.makeCurrent(); return otelScope::close; } From 33ba466ecb51c735a374114998e7872d9ee6b61a Mon Sep 17 00:00:00 2001 From: Jin Seop Kim Date: Mon, 16 Nov 2026 11:50:53 -0500 Subject: [PATCH 3/7] fix(gax): guard operationSpan and attemptSpan with ReentrantLock --- .../tracing/OpenTelemetryTracingTracer.java | 81 ++++++++++++++----- 1 file changed, 63 insertions(+), 18 deletions(-) diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java index 86c2efad5a53..c2787f2a92e1 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java @@ -42,6 +42,7 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.CancellationException; +import java.util.concurrent.locks.ReentrantLock; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @@ -61,8 +62,9 @@ class OpenTelemetryTracingTracer implements ApiTracer { private final Context parentContext; // Trace context containing the operationSpan, serving as the parent for attempt spans. private final Context operationContext; - private volatile @Nullable Span operationSpan; - private volatile @Nullable Span attemptSpan; + private final ReentrantLock spanLock = new ReentrantLock(); + private @Nullable Span operationSpan; + private @Nullable Span attemptSpan; /** * Returns the active attempt span when an attempt is in-flight, falling back to the overall @@ -71,8 +73,26 @@ class OpenTelemetryTracingTracer implements ApiTracer { * @return the current {@link Span}, or {@code null} if the operation has ended */ private @Nullable Span getCurrentSpan() { - Span currentSpan = attemptSpan; - return currentSpan != null ? currentSpan : operationSpan; + spanLock.lock(); + try { + return attemptSpan != null ? attemptSpan : operationSpan; + } finally { + spanLock.unlock(); + } + } + + /** + * Returns the active attempt span if an attempt is currently in-flight. + * + * @return the active attempt {@link Span}, or {@code null} if no attempt is active + */ + private @Nullable Span getAttemptSpan() { + spanLock.lock(); + try { + return attemptSpan; + } finally { + spanLock.unlock(); + } } /** @@ -224,7 +244,13 @@ public void attemptStarted(Object request, int attemptNumber) { // Pass the combined attributes to the new SpanBuilder method spanBuilder.setAllAttributes(ObservabilityUtils.toOtelAttributes(currentAttemptAttributes)); - this.attemptSpan = spanBuilder.startSpan(); + Span startedSpan = spanBuilder.startSpan(); + spanLock.lock(); + try { + this.attemptSpan = startedSpan; + } finally { + spanLock.unlock(); + } } /** @@ -267,13 +293,22 @@ public void operationFailed(Throwable error) { * @param error the exception associated with the operation failure, or {@code null} if successful */ private void recordErrorAndEndOperation(@Nullable Throwable error) { - if (attemptSpan != null) { - endSpan(attemptSpan, error); + Span attemptToEnd; + Span operationToEnd; + spanLock.lock(); + try { + attemptToEnd = attemptSpan; attemptSpan = null; - } - if (operationSpan != null) { - endSpan(operationSpan, error); + operationToEnd = operationSpan; operationSpan = null; + } finally { + spanLock.unlock(); + } + if (attemptToEnd != null) { + endSpan(attemptToEnd, error); + } + if (operationToEnd != null) { + endSpan(operationToEnd, error); } } @@ -284,12 +319,14 @@ public void attemptSucceeded() { @Override public void responseHeadersReceived(Map headers) { - if (attemptSpan == null) { + Span currentAttemptSpan = getAttemptSpan(); + if (currentAttemptSpan == null) { return; } long contentLength = extractContentLength(headers); if (contentLength >= 0) { - attemptSpan.setAttribute(ObservabilityAttributes.HTTP_RESPONSE_BODY_SIZE, contentLength); + currentAttemptSpan.setAttribute( + ObservabilityAttributes.HTTP_RESPONSE_BODY_SIZE, contentLength); } } @@ -350,11 +387,17 @@ public void attemptPermanentFailure(Throwable error) { * @param error the exception associated with the attempt failure, or {@code null} if successful */ private void recordErrorAndEndAttempt(@Nullable Throwable error) { - if (attemptSpan == null) { - return; + Span attemptToEnd; + spanLock.lock(); + try { + attemptToEnd = attemptSpan; + attemptSpan = null; + } finally { + spanLock.unlock(); + } + if (attemptToEnd != null) { + endSpan(attemptToEnd, error); } - endSpan(attemptSpan, error); - attemptSpan = null; } /** @@ -382,13 +425,15 @@ private void endSpan(Span span, @Nullable Throwable error) { @Override public void requestUrlResolved(String url) { - if (attemptSpan == null) { + Span currentAttemptSpan = getAttemptSpan(); + if (currentAttemptSpan == null) { return; } String sanitizedUrlString = ObservabilityUtils.sanitizeUrlFull(url); if (sanitizedUrlString.isEmpty()) { return; } - attemptSpan.setAttribute(ObservabilityAttributes.HTTP_URL_FULL_ATTRIBUTE, sanitizedUrlString); + currentAttemptSpan.setAttribute( + ObservabilityAttributes.HTTP_URL_FULL_ATTRIBUTE, sanitizedUrlString); } } From a6d3dac6ab5d6b0c7a251cb4078d365795248ea7 Mon Sep 17 00:00:00 2001 From: Jin Seop Kim Date: Mon, 16 Nov 2026 12:00:37 -0500 Subject: [PATCH 4/7] fix(gax): make OpenTelemetryTracingTracer.inScope() idempotent --- .../api/gax/tracing/OpenTelemetryTracingTracer.java | 8 +++++++- .../api/gax/tracing/OpenTelemetryTracingTracerTest.java | 6 ++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java index c2787f2a92e1..ff3a72e90867 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java @@ -42,6 +42,7 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.CancellationException; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @@ -110,7 +111,12 @@ public Scope inScope() { // Scope. @SuppressWarnings("MustBeClosedChecker") io.opentelemetry.context.Scope otelScope = currentSpan.makeCurrent(); - return otelScope::close; + AtomicBoolean closed = new AtomicBoolean(); + return () -> { + if (closed.compareAndSet(false, true)) { + otelScope.close(); + } + }; } @Override diff --git a/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpenTelemetryTracingTracerTest.java b/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpenTelemetryTracingTracerTest.java index 9abe5e91c2e1..d618bc544415 100644 --- a/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpenTelemetryTracingTracerTest.java +++ b/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpenTelemetryTracingTracerTest.java @@ -830,6 +830,12 @@ void testInScope_withAttemptSpan_activatesAttemptSpanAndFallsBackToOperationSpan } assertThat(Span.current().getSpanContext().isValid()).isFalse(); + // Calling close() multiple times is idempotent + ApiTracer.Scope manualScope = openTelemetryTracingTracer.inScope(); + manualScope.close(); + manualScope.close(); + assertThat(Span.current().getSpanContext().isValid()).isFalse(); + // After operation ends, inScope() is a no-op openTelemetryTracingTracer.operationSucceeded(); try (ApiTracer.Scope ignored = openTelemetryTracingTracer.inScope()) { From aae523d951d57aafa22f2c0ba125bdf1ab86f230 Mon Sep 17 00:00:00 2001 From: Jin Seop Kim Date: Mon, 16 Nov 2026 12:07:38 -0500 Subject: [PATCH 5/7] fix(gax): replace AtomicBoolean with anonymous Scope in OpenTelemetryTracingTracer.inScope() --- .../gax/tracing/OpenTelemetryTracingTracer.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java index ff3a72e90867..951cd11cae9d 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java @@ -42,7 +42,6 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.CancellationException; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @@ -111,10 +110,15 @@ public Scope inScope() { // Scope. @SuppressWarnings("MustBeClosedChecker") io.opentelemetry.context.Scope otelScope = currentSpan.makeCurrent(); - AtomicBoolean closed = new AtomicBoolean(); - return () -> { - if (closed.compareAndSet(false, true)) { - otelScope.close(); + return new Scope() { + private boolean closed; + + @Override + public void close() { + if (!closed) { + closed = true; + otelScope.close(); + } } }; } From 349210e014cd88697d69595089de4ff25adba046 Mon Sep 17 00:00:00 2001 From: Jin Seop Kim Date: Mon, 16 Nov 2026 12:15:32 -0500 Subject: [PATCH 6/7] fix(gax): annotate span fields with @GuardedBy("spanLock") --- .../gax/tracing/OpenTelemetryTracingTracer.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java index 951cd11cae9d..53b5afd67a29 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java @@ -32,6 +32,7 @@ import com.google.api.client.util.Strings; import com.google.api.core.InternalApi; +import com.google.errorprone.annotations.concurrent.GuardedBy; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanBuilder; import io.opentelemetry.api.trace.SpanKind; @@ -63,7 +64,11 @@ class OpenTelemetryTracingTracer implements ApiTracer { // Trace context containing the operationSpan, serving as the parent for attempt spans. private final Context operationContext; private final ReentrantLock spanLock = new ReentrantLock(); + + @GuardedBy("spanLock") private @Nullable Span operationSpan; + + @GuardedBy("spanLock") private @Nullable Span attemptSpan; /** @@ -170,8 +175,14 @@ public void injectTraceContext(Map carrier) { this.attemptAttributes = new HashMap<>(); this.parentContext = Context.current(); buildAttributes(); - this.operationSpan = startOperationSpan(); - this.operationContext = parentContext.with(this.operationSpan); + Span initialOperationSpan = startOperationSpan(); + spanLock.lock(); + try { + this.operationSpan = initialOperationSpan; + } finally { + spanLock.unlock(); + } + this.operationContext = parentContext.with(initialOperationSpan); } /** From 0df1aea94e8207677b736146f29d3b18d9753799 Mon Sep 17 00:00:00 2001 From: Jin Seop Kim Date: Mon, 16 Nov 2026 13:50:37 -0500 Subject: [PATCH 7/7] fix(gax): simplify OpenTelemetryTracingTracer.inScope() to minimal volatile implementation --- .../tracing/OpenTelemetryTracingTracer.java | 122 ++++-------------- .../OpenTelemetryTracingTracerTest.java | 6 - 2 files changed, 24 insertions(+), 104 deletions(-) diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java index 53b5afd67a29..f106563f067d 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryTracingTracer.java @@ -32,7 +32,6 @@ import com.google.api.client.util.Strings; import com.google.api.core.InternalApi; -import com.google.errorprone.annotations.concurrent.GuardedBy; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanBuilder; import io.opentelemetry.api.trace.SpanKind; @@ -43,7 +42,6 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.CancellationException; -import java.util.concurrent.locks.ReentrantLock; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @@ -63,42 +61,8 @@ class OpenTelemetryTracingTracer implements ApiTracer { private final Context parentContext; // Trace context containing the operationSpan, serving as the parent for attempt spans. private final Context operationContext; - private final ReentrantLock spanLock = new ReentrantLock(); - - @GuardedBy("spanLock") - private @Nullable Span operationSpan; - - @GuardedBy("spanLock") - private @Nullable Span attemptSpan; - - /** - * Returns the active attempt span when an attempt is in-flight, falling back to the overall - * operation span when between attempts or at operation completion. - * - * @return the current {@link Span}, or {@code null} if the operation has ended - */ - private @Nullable Span getCurrentSpan() { - spanLock.lock(); - try { - return attemptSpan != null ? attemptSpan : operationSpan; - } finally { - spanLock.unlock(); - } - } - - /** - * Returns the active attempt span if an attempt is currently in-flight. - * - * @return the active attempt {@link Span}, or {@code null} if no attempt is active - */ - private @Nullable Span getAttemptSpan() { - spanLock.lock(); - try { - return attemptSpan; - } finally { - spanLock.unlock(); - } - } + private volatile @Nullable Span operationSpan; + private volatile @Nullable Span attemptSpan; /** * Activates the current span on the calling thread's OpenTelemetry {@link Context}. @@ -107,7 +71,10 @@ class OpenTelemetryTracingTracer implements ApiTracer { */ @Override public Scope inScope() { - Span currentSpan = getCurrentSpan(); + Span currentSpan = attemptSpan; + if (currentSpan == null) { + currentSpan = operationSpan; + } if (currentSpan == null) { return () -> {}; } @@ -115,24 +82,14 @@ public Scope inScope() { // Scope. @SuppressWarnings("MustBeClosedChecker") io.opentelemetry.context.Scope otelScope = currentSpan.makeCurrent(); - return new Scope() { - private boolean closed; - - @Override - public void close() { - if (!closed) { - closed = true; - otelScope.close(); - } - } - }; + return otelScope::close; } @Override public void injectTraceContext(Map carrier) { // Prefer the active attempt span so outgoing RPC wire context reflects the specific attempt; // fall back to the overall operation span if no attempt is currently in-flight. - Span currentSpan = getCurrentSpan(); + Span currentSpan = attemptSpan != null ? attemptSpan : operationSpan; if (currentSpan != null) { Context context = Context.current().with(currentSpan); W3CTraceContextPropagator.getInstance() @@ -175,14 +132,8 @@ public void injectTraceContext(Map carrier) { this.attemptAttributes = new HashMap<>(); this.parentContext = Context.current(); buildAttributes(); - Span initialOperationSpan = startOperationSpan(); - spanLock.lock(); - try { - this.operationSpan = initialOperationSpan; - } finally { - spanLock.unlock(); - } - this.operationContext = parentContext.with(initialOperationSpan); + this.operationSpan = startOperationSpan(); + this.operationContext = parentContext.with(this.operationSpan); } /** @@ -265,13 +216,7 @@ public void attemptStarted(Object request, int attemptNumber) { // Pass the combined attributes to the new SpanBuilder method spanBuilder.setAllAttributes(ObservabilityUtils.toOtelAttributes(currentAttemptAttributes)); - Span startedSpan = spanBuilder.startSpan(); - spanLock.lock(); - try { - this.attemptSpan = startedSpan; - } finally { - spanLock.unlock(); - } + this.attemptSpan = spanBuilder.startSpan(); } /** @@ -314,22 +259,13 @@ public void operationFailed(Throwable error) { * @param error the exception associated with the operation failure, or {@code null} if successful */ private void recordErrorAndEndOperation(@Nullable Throwable error) { - Span attemptToEnd; - Span operationToEnd; - spanLock.lock(); - try { - attemptToEnd = attemptSpan; + if (attemptSpan != null) { + endSpan(attemptSpan, error); attemptSpan = null; - operationToEnd = operationSpan; - operationSpan = null; - } finally { - spanLock.unlock(); - } - if (attemptToEnd != null) { - endSpan(attemptToEnd, error); } - if (operationToEnd != null) { - endSpan(operationToEnd, error); + if (operationSpan != null) { + endSpan(operationSpan, error); + operationSpan = null; } } @@ -340,14 +276,12 @@ public void attemptSucceeded() { @Override public void responseHeadersReceived(Map headers) { - Span currentAttemptSpan = getAttemptSpan(); - if (currentAttemptSpan == null) { + if (attemptSpan == null) { return; } long contentLength = extractContentLength(headers); if (contentLength >= 0) { - currentAttemptSpan.setAttribute( - ObservabilityAttributes.HTTP_RESPONSE_BODY_SIZE, contentLength); + attemptSpan.setAttribute(ObservabilityAttributes.HTTP_RESPONSE_BODY_SIZE, contentLength); } } @@ -408,17 +342,11 @@ public void attemptPermanentFailure(Throwable error) { * @param error the exception associated with the attempt failure, or {@code null} if successful */ private void recordErrorAndEndAttempt(@Nullable Throwable error) { - Span attemptToEnd; - spanLock.lock(); - try { - attemptToEnd = attemptSpan; - attemptSpan = null; - } finally { - spanLock.unlock(); - } - if (attemptToEnd != null) { - endSpan(attemptToEnd, error); + if (attemptSpan == null) { + return; } + endSpan(attemptSpan, error); + attemptSpan = null; } /** @@ -446,15 +374,13 @@ private void endSpan(Span span, @Nullable Throwable error) { @Override public void requestUrlResolved(String url) { - Span currentAttemptSpan = getAttemptSpan(); - if (currentAttemptSpan == null) { + if (attemptSpan == null) { return; } String sanitizedUrlString = ObservabilityUtils.sanitizeUrlFull(url); if (sanitizedUrlString.isEmpty()) { return; } - currentAttemptSpan.setAttribute( - ObservabilityAttributes.HTTP_URL_FULL_ATTRIBUTE, sanitizedUrlString); + attemptSpan.setAttribute(ObservabilityAttributes.HTTP_URL_FULL_ATTRIBUTE, sanitizedUrlString); } } diff --git a/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpenTelemetryTracingTracerTest.java b/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpenTelemetryTracingTracerTest.java index d618bc544415..9abe5e91c2e1 100644 --- a/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpenTelemetryTracingTracerTest.java +++ b/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/tracing/OpenTelemetryTracingTracerTest.java @@ -830,12 +830,6 @@ void testInScope_withAttemptSpan_activatesAttemptSpanAndFallsBackToOperationSpan } assertThat(Span.current().getSpanContext().isValid()).isFalse(); - // Calling close() multiple times is idempotent - ApiTracer.Scope manualScope = openTelemetryTracingTracer.inScope(); - manualScope.close(); - manualScope.close(); - assertThat(Span.current().getSpanContext().isValid()).isFalse(); - // After operation ends, inScope() is a no-op openTelemetryTracingTracer.operationSucceeded(); try (ApiTracer.Scope ignored = openTelemetryTracingTracer.inScope()) {