Skip to content

Flink dropping watermarks hold fix - #40149

Merged
damccorm merged 4 commits into
apache:masterfrom
CarloMariaProietti:flink_dropping_watermarks_fix
Oct 12, 2026
Merged

damccorm merged 4 commits into
apache:masterfrom
CarloMariaProietti:flink_dropping_watermarks_fix

Conversation

@CarloMariaProietti

@CarloMariaProietti CarloMariaProietti commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Please add a meaningful description for your change here

Fixes #39991

Problem:
The BufferingDoFnRunner class has the following issue: the minBufferedElementTimestamp field is intended to hold the minimum timestamp among all elements in currentBufferingElementsHandler. This semantic contract can be observed in the processElement and onTimer methods. However, checkpointCompleted violates this contract by setting minBufferedElementTimestamp to Long.MAX_VALUE without guaranteeing that currentBufferingElementsHandler is completely empty (while likely, it is not guaranteed; see #39991 for details).

Solution:
checkpointCompleted now sets minBufferedElementTimestamp to Long.MAX_VALUE only if currentBufferingElementsHandler is empty; otherwise, it recomputes the minimum timestamp according to its semantic invariant.

Implementation Details:
Implemented following the GRASP Polymorphism pattern. The semantics across implementations of the polymorphic getTimestamp method remain consistent with processElement and onTimer.

Testing:
Added a regression test (testExactlyOnceBufferingOutputWatermarkCorrectness) in DoFnOperatorTest that reproduces the issue described in #39991.

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.

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @jrmccluskey added as fallback since no labels match configuration

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).

@CarloMariaProietti CarloMariaProietti changed the title Flink dropping watermarks fix Flink dropping watermarks hold fix Sep 17, 2026
@jrmccluskey

Copy link
Copy Markdown
Contributor

R: @bvolpato

@github-actions

Copy link
Copy Markdown
Contributor

Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment assign set of reviewers

@damccorm damccorm 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.

Thanks for tracking down and fixing this issue! Left a couple of comments regarding concurrent checkpoints / state reads and a small test nit.

Comment on lines +302 to +307
minBufferedElementTimestamp =
currentBufferingElementsHandler
.getElements()
.mapToLong(e -> e.getTimestamp().getMillis())
.min()
.orElse(Long.MAX_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.

A few thoughts on how minBufferedElementTimestamp is recomputed here:

  1. Concurrent checkpoints (maxConcurrentCheckpoints > 1): If checkpoint N completes while checkpoint N+1 has already been snapshotted (and is still pending in notYetAcknowledgedSnapshots), currentBufferingElementsHandler has already rotated to the buffer for N+2. Only checking currentBufferingElementsHandler will miss elements still buffered in unacknowledged checkpoint N+1 and can drop their watermark hold.
  2. Locking (Locker): When using KeyedBufferingElementsHandler (e.g., in ExecutableStageDoFnOperator), getElements() iterates keys and calls backend.setCurrentKey(key) / state.get() on the KeyedStateBackend. All other accesses to BufferingElementsHandler in this class are guarded by try (Locker lock = locker != null ? locker.get() : null).
  3. Avoiding extra state reads/deserialization: Calling currentBufferingElementsHandler.getElements() on every checkpointCompleted forces Flink to read and deserialize all buffered elements in the active buffer (and scan all keys in RocksDB when keyed), only to read and deserialize them again when the next checkpoint completes.

Could we instead track the minimum timestamp per buffer index in memory (e.g., a long[] minTimestampPerBuffer of size numCheckpointBuffers initialized to Long.MAX_VALUE)?

  • In processElement / onTimer, update minTimestampPerBuffer[currentStateIndex] (and minBufferedElementTimestamp).
  • In checkpointCompleted, reset minTimestampPerBuffer[toBeAcked.internalId] = Long.MAX_VALUE as each buffer is cleared, and then set minBufferedElementTimestamp to the min across minTimestampPerBuffer.

That would avoid scanning/deserializing Flink state in checkpointCompleted, avoid the Locker issue, and naturally preserve watermark holds across multiple concurrent checkpoints. (If we also want holds preserved across job restarts, we could populate minTimestampPerBuffer from pendingSnapshots once in initializeState.)

Comment on lines +2268 to +2316
Supplier<DoFnOperator<String, String, String>> doFnOperatorSupplier =
() ->
new DoFnOperator<>(
doFn,
"stepName",
windowedValueCoder,
Collections.emptyMap(),
outputTag,
Collections.emptyList(),
outputManagerFactory,
WindowingStrategy.globalDefault(),
new HashMap<>(), /* side-input mapping */
Collections.emptyList(), /* side inputs */
options,
null,
null,
DoFnSchemaInformation.create(),
Collections.emptyMap());

DoFnOperator<String, String, String> doFnOperator = doFnOperatorSupplier.get();
OneInputStreamOperatorTestHarness<WindowedValue<String>, WindowedValue<String>> testHarness =
new OneInputStreamOperatorTestHarness<>(doFnOperator);

testHarness.open();

testHarness.processElement(
new StreamRecord<>(WindowedValues.timestampedValueInGlobalWindow("A", new Instant(10))));
testHarness.snapshot(1L, 0L);
testHarness.processElement(
new StreamRecord<>(WindowedValues.timestampedValueInGlobalWindow("B", new Instant(20))));
testHarness.processWatermark(new Watermark(100));
assertThat(
"A@10 has not yet completed the checkpoint; output watermark must be held at 10 until checkpoint completion",
doFnOperator.getCurrentOutputWatermark(),
is(10L));

doFnOperator.notifyCheckpointComplete(1L);
assertThat(
"A@10 has been checked but B@20 is still buffered; output watermark must not pass it",
doFnOperator.getCurrentOutputWatermark(),
is(20L));

testHarness.snapshot(2L, 0L);
doFnOperator.notifyCheckpointComplete(2L);
assertThat(
"B@20 has been checked and the buffer is empty; output watermark must advance to input watermark",
doFnOperator.getCurrentOutputWatermark(),
is(100L));
}

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.

Nit: Since this test doesn't restore from a snapshot, doFnOperatorSupplier can be inlined to construct doFnOperator directly, and we should call testHarness.close() at the end (or use try-with-resources). Also might be nice to assert on testHarness.getOutput() at the end to verify that A@10 and B@20 were emitted in order before watermark 100.

@kennknowles
kennknowles removed their request for review October 8, 2026 12:50
@CarloMariaProietti

CarloMariaProietti commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

@damccorm Thank you for reviewing! I've fixed the logic in DoFnOperator so that the minimum timestamp is tracked per checkpoint buffer and extended the test to cover your point. Please let me know whether watermark holds should be preserved across job restarts.

@damccorm damccorm 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.

Thanks!

@damccorm

damccorm commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Making sure workflows succeed before proceeding

@codecov

codecov Bot commented Oct 9, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.42857% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 58.73%. Comparing base (76f6e6d) to head (d96cc98).
⚠️ Report is 110 commits behind head on master.

Files with missing lines Patch % Lines
...ers/streaming/stableinput/BufferingDoFnRunner.java 71.42% 4 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #40149      +/-   ##
============================================
+ Coverage     56.16%   58.73%   +2.56%     
- Complexity     2288    13919   +11631     
============================================
  Files          1124     2585    +1461     
  Lines        178336   271702   +93366     
  Branches       1489    11243    +9754     
============================================
+ Hits         100170   159593   +59423     
- Misses        75645   106107   +30462     
- Partials       2521     6002    +3481     
Flag Coverage Δ
java 65.27% <71.42%> (-10.52%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@damccorm
damccorm merged commit 8d8b549 into apache:master Oct 12, 2026
35 of 38 checks passed
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.

[Bug]: Flink drops watermark holds for records awaiting a checkpoint

3 participants