Skip to content

Add drain support for Dataflow and Flink#38786

Open
lalitx17 wants to merge 3 commits into
apache:masterfrom
lalitx17:pipeline-result-drain
Open

Add drain support for Dataflow and Flink#38786
lalitx17 wants to merge 3 commits into
apache:masterfrom
lalitx17:pipeline-result-drain

Conversation

@lalitx17
Copy link
Copy Markdown
Contributor

@lalitx17 lalitx17 commented Jun 3, 2026

Adds Java SDK pipeline drain support for Dataflow and Flink.

This change adds PipelineResult#drain() as a default SDK method and introduces two new pipeline states:

  • DRAINING
  • DRAINED

Dataflow now requests drain by updating the job requested state to JOB_STATE_DRAINED, and maps Dataflow drain states precisely:

  • JOB_STATE_DRAINING -> PipelineResult.State.DRAINING
  • JOB_STATE_DRAINED -> PipelineResult.State.DRAINED

Flink detached results now support drain through JobClient#stopWithSavepoint(...), returning DRAINING while the stop/savepoint operation is pending and DRAINED after it completes.

addresses #38771


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.

Copilot AI review requested due to automatic review settings June 3, 2026 13:46
@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 adds support for draining pipelines in the Apache Beam Java SDK, enabling runners to stop accepting new input while finishing the processing of existing data. It updates the core SDK to include new pipeline states and provides implementations for both the Dataflow and Flink runners to handle these drain requests effectively.

Highlights

  • Pipeline Drain Support: Introduced PipelineResult#drain() as a default SDK method to allow graceful shutdown of pipelines by processing remaining data.
  • New Pipeline States: Added DRAINING and DRAINED states to PipelineResult.State to track the lifecycle of a drain operation.
  • Runner Implementations: Implemented drain support for Dataflow by mapping to JOB_STATE_DRAINED and for Flink by utilizing JobClient#stopWithSavepoint.
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.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Adds a first-class “drain” lifecycle operation to PipelineResult, introducing explicit DRAINING / DRAINED states and updating Dataflow + Flink runners to support and test these semantics.

Changes:

  • Added PipelineResult#drain() default API and new PipelineResult.State values DRAINING and DRAINED.
  • Updated Dataflow state mapping and DataflowPipelineJob to issue drain requests, plus added/updated tests.
  • Implemented drain support for Flink runner results (done + detached cases) with tests.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
sdks/java/core/src/main/java/org/apache/beam/sdk/PipelineResult.java Introduces drain() API + DRAINING/DRAINED states in the core contract.
runners/google-cloud-dataflow-java/src/main/java/org/apache/beam/runners/dataflow/util/MonitoringUtil.java Maps Dataflow service drain states to the new Beam states.
runners/google-cloud-dataflow-java/src/test/java/org/apache/beam/runners/dataflow/util/MonitoringUtilTest.java Updates assertions to validate the new drain state mapping.
runners/google-cloud-dataflow-java/src/main/java/org/apache/beam/runners/dataflow/DataflowPipelineJob.java Implements drain via a generalized lifecycle request helper and logs terminal DRAINED.
runners/google-cloud-dataflow-java/src/test/java/org/apache/beam/runners/dataflow/DataflowPipelineJobTest.java Adds a unit test validating drain request behavior.
runners/google-cloud-dataflow-java/src/main/java/org/apache/beam/runners/dataflow/TestDataflowRunner.java Treats DRAINED as a successful terminal condition for termination waits.
runners/flink/src/main/java/org/apache/beam/runners/flink/FlinkRunnerResult.java Implements a no-op drain() returning DONE for already-finished results.
runners/flink/src/main/java/org/apache/beam/runners/flink/FlinkDetachedRunnerResult.java Implements detached drain using stopWithSavepoint, exposing DRAINING/DRAINED.
runners/flink/src/test/java/org/apache/beam/runners/flink/FlinkRunnerResultTest.java Adds tests validating drain semantics for Flink (done + detached).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.


private JobClient jobClient;
private int jobCheckIntervalInSecs;
private @Nullable CompletableFuture<String> drainSavepointFuture;
Comment on lines +54 to +57
CompletableFuture<String> drainFuture = drainSavepointFuture;
if (drainFuture != null) {
return getDrainState(drainFuture);
}
Comment on lines +94 to +101
public synchronized State drain() throws IOException {
CompletableFuture<String> drainFuture = drainSavepointFuture;
if (drainFuture == null) {
drainFuture = this.jobClient.stopWithSavepoint(true, null, SavepointFormatType.DEFAULT);
drainSavepointFuture = drainFuture;
}
return getDrainState(drainFuture);
}
Comment on lines +112 to +115
throw new RuntimeException("Fail to drain flink job", e);
} catch (ExecutionException e) {
throw new RuntimeException("Fail to drain flink job", e);
}
capitalizedAction,
state);
return state;
} else if (e.getMessage().contains("has terminated")) {
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

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 support for draining pipelines across Flink and Google Cloud Dataflow runners by implementing the drain() method and adding DRAINING and DRAINED states to the Beam SDK. Key feedback focuses on improving thread safety and robustness, specifically by declaring the drainSavepointFuture field as volatile, handling exceptional completion in getState(), allowing retries and throwing checked IOExceptions in the Flink runner's drain() implementation, and adding a null check to prevent a potential NullPointerException when reading exception messages in the Dataflow runner.

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.


private JobClient jobClient;
private int jobCheckIntervalInSecs;
private @Nullable CompletableFuture<String> drainSavepointFuture;
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

The drainSavepointFuture field is read in getState() without synchronization, but written in the synchronized drain() method. To ensure proper visibility and thread safety across threads, this field should be declared as volatile.

Suggested change
private @Nullable CompletableFuture<String> drainSavepointFuture;
private volatile @Nullable CompletableFuture<String> drainSavepointFuture;

Comment on lines +54 to +57
CompletableFuture<String> drainFuture = drainSavepointFuture;
if (drainFuture != null) {
return getDrainState(drainFuture);
}
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

If the drainSavepointFuture completes exceptionally (e.g., if the stop-with-savepoint operation fails), calling getState() will currently throw a RuntimeException and crash the caller. Instead, we should be more robust: if the drain operation failed, the job is likely still running or in its previous state. We can check isCompletedExceptionally() and, if true, fall back to querying the actual Flink job status via jobClient.getJobStatus().

Suggested change
CompletableFuture<String> drainFuture = drainSavepointFuture;
if (drainFuture != null) {
return getDrainState(drainFuture);
}
CompletableFuture<String> drainFuture = drainSavepointFuture;
if (drainFuture != null && !drainFuture.isCompletedExceptionally()) {
return drainFuture.isDone() ? State.DRAINED : State.DRAINING;
}

Comment on lines +94 to +116
public synchronized State drain() throws IOException {
CompletableFuture<String> drainFuture = drainSavepointFuture;
if (drainFuture == null) {
drainFuture = this.jobClient.stopWithSavepoint(true, null, SavepointFormatType.DEFAULT);
drainSavepointFuture = drainFuture;
}
return getDrainState(drainFuture);
}

private State getDrainState(CompletableFuture<String> drainFuture) {
if (!drainFuture.isDone()) {
return State.DRAINING;
}
try {
drainFuture.get();
return State.DRAINED;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Fail to drain flink job", e);
} catch (ExecutionException e) {
throw new RuntimeException("Fail to drain flink job", e);
}
}
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

We can improve the robustness of the drain() method in several ways:

  1. Support Retries: If a previous drain attempt failed (i.e., drainFuture.isCompletedExceptionally()), we should allow the user to retry the drain operation rather than permanently returning the cached failure.
  2. Throw Checked Exceptions: Since drain() is declared to throw IOException, we should wrap and throw IOException instead of RuntimeException when the future fails.
  3. Simplify Code: We can inline the getDrainState logic directly into drain() and remove the helper method entirely, making the code cleaner.
  @Override
  public synchronized State drain() throws IOException {
    CompletableFuture<String> drainFuture = drainSavepointFuture;
    if (drainFuture == null || drainFuture.isCompletedExceptionally()) {
      drainFuture = this.jobClient.stopWithSavepoint(true, null, SavepointFormatType.DEFAULT);
      drainSavepointFuture = drainFuture;
    }
    if (!drainFuture.isDone()) {
      return State.DRAINING;
    }
    try {
      drainFuture.get();
      return State.DRAINED;
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new IOException("Failed to drain flink job", e);
    } catch (ExecutionException e) {
      throw new IOException("Failed to drain flink job", e.getCause());
    }
  }

capitalizedAction,
state);
return state;
} else if (e.getMessage().contains("has terminated")) {
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

If e.getMessage() is null (which can happen with certain IOException subclasses or in test environments), calling contains() on it will throw a NullPointerException, masking the original exception. We should add a null check before calling contains().

Suggested change
} else if (e.getMessage().contains("has terminated")) {
} else if (e.getMessage() != null && e.getMessage().contains("has terminated")) {

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Jun 3, 2026

Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment assign set of reviewers

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.

2 participants