Skip to content

[OpenTelemetry] Add tracing support to GCP PubsubIO#39150

Open
stankiewicz wants to merge 1 commit into
apache:masterfrom
stankiewicz:otel_pubsub
Open

[OpenTelemetry] Add tracing support to GCP PubsubIO#39150
stankiewicz wants to merge 1 commit into
apache:masterfrom
stankiewicz:otel_pubsub

Conversation

@stankiewicz

Copy link
Copy Markdown
Contributor

This PR introduces OpenTelemetry (OTel) support for Google Cloud Pub/Sub IO, enabling distributed tracing and better observability for Pub/Sub operations within Apache Beam pipelines.

  • Configuration: Added withEnableOpenTelemetryTracing() configuration methods to both PubsubIO.Read and PubsubIO.Write builders to allow users to toggle OTel tracing.

  • Context Propagation (Write): Introduced the OpenTelemetryHeaderPropagator DoFn. When OTel is enabled, this function injects the current OpenTelemetry trace context into outbound PubsubMessage attributes (using the googclient_ prefix) via the W3C Trace Context propagator.

  • Context Extraction (Read): Introduced the OpenTelemetryHeaderConsumer DoFn. When OTel is enabled, this function extracts the trace context from incoming PubsubMessage attributes and sets it as the parent span context for the "Process Element" span, linking the distributed trace.

  • Validation Fix: Updated the validation logic in PubsubIO.Read.expand() to properly throw an IllegalArgumentException if both a dead letter topic and a custom bad record router are configured.


Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • Mention the appropriate issue in your description (for example: addresses #123), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment fixes #<ISSUE NUMBER> instead.
  • Update CHANGES.md with noteworthy changes.
  • If this contribution is large, please file an Apache Individual Contributor License Agreement.

See the Contributor Guide for more tips on how to make review process smoother.

To check the build health, please visit https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md

GitHub Actions Tests Status (on master branch)

Build python source distribution and wheels
Python tests
Java tests
Go tests

See CI.md for more information about GitHub Actions CI or the workflows README to see a list of phrases to trigger workflows.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances observability in Apache Beam by integrating OpenTelemetry tracing into the Google Cloud Pub/Sub IO connector. By allowing trace context propagation through Pub/Sub message attributes, it enables seamless distributed tracing for data pipelines. Additionally, the change includes a necessary fix to the validation logic for error handling configurations.

Highlights

  • OpenTelemetry Integration: Added OpenTelemetry tracing support to PubsubIO for both reading and writing, enabling distributed tracing across Apache Beam pipelines.
  • Context Propagation: Implemented OpenTelemetryHeaderPropagator and OpenTelemetryHeaderConsumer to inject and extract trace contexts via W3C Trace Context headers in Pub/Sub message attributes.
  • Configuration: Introduced withEnableOpenTelemetryTracing() methods to PubsubIO.Read and PubsubIO.Write builders to allow users to toggle tracing functionality.
  • Validation Fix: Corrected the validation logic in PubsubIO.Read to properly throw an IllegalArgumentException when both a dead letter topic and a custom bad record router are configured.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces OpenTelemetry tracing support to PubsubIO's read and write transforms by extracting and propagating trace contexts via message attributes. However, several critical issues were identified in the implementation: a logic inversion bug was introduced in the dead-letter topic validation; the TextMapGetter implementation in OpenTelemetryHeaderConsumer has potential null-pointer issues, incorrect return values, and inconsistent key mapping; the newly created tracing span is not correctly made current; and OpenTelemetryHeaderPropagator is susceptible to NullPointerExceptions when message attributes are null.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines 1190 to 1194
if (getDeadLetterTopicProvider() != null
&& !(getBadRecordRouter() instanceof ThrowingBadRecordRouter)) {
&& (getBadRecordRouter() instanceof ThrowingBadRecordRouter)) {
throw new IllegalArgumentException(
"PubSubIO cannot be configured with both a dead letter topic and a bad record router");
}

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.

critical

This change introduces a critical logic inversion bug. The original code threw an exception if a dead letter topic was configured AND a custom bad record router was used (i.e., not the default ThrowingBadRecordRouter). By changing !(...) to (...), the code now throws an exception when a dead letter topic is configured with the DEFAULT ThrowingBadRecordRouter, which completely breaks the standard dead letter topic configuration for all users.

Suggested change
if (getDeadLetterTopicProvider() != null
&& !(getBadRecordRouter() instanceof ThrowingBadRecordRouter)) {
&& (getBadRecordRouter() instanceof ThrowingBadRecordRouter)) {
throw new IllegalArgumentException(
"PubSubIO cannot be configured with both a dead letter topic and a bad record router");
}
if (getDeadLetterTopicProvider() != null
&& !(getBadRecordRouter() instanceof ThrowingBadRecordRouter)) {
throw new IllegalArgumentException(
"PubSubIO cannot be configured with both a dead letter topic and a bad record router");
}

Comment on lines +1102 to +1120
Context extractSpanContext(PubsubMessage message) {
TextMapGetter<PubsubMessage> extractMessageAttributes =
new TextMapGetter<PubsubMessage>() {
@Override
public String get(@Nullable PubsubMessage carrier, String key) {
String attribute =
Preconditions.checkArgumentNotNull(carrier).getAttribute("googclient_" + key);
return attribute == null ? "" : attribute;
}

@Override
public Iterable<String> keys(PubsubMessage carrier) {
Map<String, String> attributeMap = carrier.getAttributeMap();
return attributeMap == null ? ImmutableList.of() : attributeMap.keySet();
}
};
return W3CTraceContextPropagator.getInstance()
.extract(Context.current(), message, extractMessageAttributes);
}

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.

high

There are three issues with the TextMapGetter implementation:

  1. If carrier is null, get will throw a NullPointerException due to Preconditions.checkArgumentNotNull(carrier). According to the OpenTelemetry specification, get should return null if the carrier is null or the key is not found.
  2. Returning "" (empty string) instead of null when the attribute is missing can cause the propagator to fail or log warnings because it tries to parse an empty string as a traceparent.
  3. keys returns the raw keys from the attribute map (e.g., "googclient_traceparent"). However, get prepends "googclient_" to the key. If a propagator iterates over the keys returned by keys and calls get, it will look up "googclient_googclient_traceparent". keys should filter and strip the "googclient_" prefix to remain consistent with get.
      Context extractSpanContext(PubsubMessage message) {
        TextMapGetter<PubsubMessage> extractMessageAttributes =
            new TextMapGetter<PubsubMessage>() {
              @Override
              public String get(@Nullable PubsubMessage carrier, String key) {
                if (carrier == null) {
                  return null;
                }
                return carrier.getAttribute("googclient_" + key);
              }

              @Override
              public Iterable<String> keys(PubsubMessage carrier) {
                if (carrier == null) {
                  return ImmutableList.of();
                }
                Map<String, String> attributeMap = carrier.getAttributeMap();
                if (attributeMap == null) {
                  return ImmutableList.of();
                }
                java.util.List<String> keys = new java.util.ArrayList<>();
                for (String key : attributeMap.keySet()) {
                  if (key.startsWith("googclient_")) {
                    keys.add(key.substring("googclient_".length()));
                  }
                }
                return keys;
              }
            };
        return W3CTraceContextPropagator.getInstance()
            .extract(Context.current(), message, extractMessageAttributes);
      }

Comment on lines +1133 to +1135
try (Scope s = context.makeCurrent()) {
output.output(message);
} finally {

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.

high

The scope is being created using context.makeCurrent() instead of psSub.makeCurrent(). This means the newly created span psSub is never made current, and any downstream operations or nested spans created during output.output(message) will not be children of psSub ("Process Element"). Instead, they will be direct children of the extracted parent context.

Suggested change
try (Scope s = context.makeCurrent()) {
output.output(message);
} finally {
try (Scope s = psSub.makeCurrent()) {
output.output(message);
} finally {

Comment on lines +1534 to +1536
Map<String, String> attributeMap = message.getAttributeMap();
Map<String, String> attr = new HashMap<>(Objects.requireNonNull(attributeMap));
injectSpanContext(attr);

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.

high

message.getAttributeMap() can return null if the PubsubMessage was constructed without attributes. Calling Objects.requireNonNull(attributeMap) will throw a NullPointerException at runtime. We should handle the null case gracefully by initializing an empty HashMap.

Suggested change
Map<String, String> attributeMap = message.getAttributeMap();
Map<String, String> attr = new HashMap<>(Objects.requireNonNull(attributeMap));
injectSpanContext(attr);
Map<String, String> attributeMap = message.getAttributeMap();
Map<String, String> attr =
attributeMap == null ? new HashMap<>() : new HashMap<>(attributeMap);
injectSpanContext(attr);

Comment on lines +1517 to +1524
void injectSpanContext(Map<String, String> attr) {
TextMapSetter<Map<String, String>> inject =
new TextMapSetter<Map<String, String>>() {
@Override
public void set(@Nullable Map<String, String> attr, String key, String value) {
Preconditions.checkArgumentNotNull(attr).put("googclient_" + key, value);
}
};

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.

medium

Using Preconditions.checkArgumentNotNull(attr) inside the TextMapSetter is risky because the setter's contract allows attr to be @Nullable. It is safer to perform a null check and skip injection if attr is null.

      void injectSpanContext(Map<String, String> attr) {
        TextMapSetter<Map<String, String>> inject =
            new TextMapSetter<Map<String, String>>() {
              @Override
              public void set(@Nullable Map<String, String> attr, String key, String value) {
                if (attr != null) {
                  attr.put("googclient_" + key, value);
                }
              }
            };

@stankiewicz stankiewicz force-pushed the otel_pubsub branch 2 times, most recently from 8859ba1 to d902a71 Compare June 29, 2026 13:37
@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @Abacn for label java.

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant