Skip to content

[KafkaIO] Advance idle partition watermark without requiring a record - #40176

Open
udayaw wants to merge 2 commits into
apache:masterfrom
udayaw:fix-dataflow-high-watermark
Open

udayaw wants to merge 2 commits into
apache:masterfrom
udayaw:fix-dataflow-high-watermark

Conversation

@udayaw

@udayaw udayaw commented Sep 18, 2026

Copy link
Copy Markdown
Contributor

Might be related to #20908

Problem

CustomTimestampPolicyWithLimitedDelay.getWatermark only advances an idle
partition when three things are true:

  1. ctx.getMessageBacklog() == 0
  2. ctx.getBacklogCheckTime().minus(maxDelay).isAfter(maxEventTimestamp)
  3. maxEventTimestamp.getMillis() > 0"Read at least one record with a positive timestamp."

maxEventTimestamp starts at previousWatermark.orElse(TIMESTAMP_MIN_VALUE).plus(maxDelay),
and only getTimestampForRecord ever raises it. So if a partition is caught up
but hasn't delivered anything since the job started, check 3 never passes:

maxEventTimestamp = TIMESTAMP_MIN_VALUE + maxDelay   // negative, check 3 fails
getWatermark()    → maxEventTimestamp.minus(maxDelay)
                  = TIMESTAMP_MIN_VALUE

It stays there until that partition's first record shows up. A stage takes the
minimum watermark across its partitions, so one quiet partition holds back the
whole stage.

It's also sticky. The policy is rebuilt every bundle, but previousWatermark
carries the floor value over, so a pinned partition stays pinned.

Two things have to line up: the partition is caught up, and it hasn't delivered
a record. Being caught up is what makes holding wrong — if there were unread
data, holding at the floor would make sense, since you don't know what
timestamps are coming.

Impact

Depends on the pipeline. With event-time windows nothing closes, so aggregations
don't fire and output never comes out — the symptom in #20908. With
processing-time triggers output is fine, but the watermark is meaningless:
TIMESTAMP_MIN_VALUE just means "no watermark yet", so data freshness can't tell
a caught-up stage from a stuck one.

We hit this on Dataflow, with a lot of partitions pinned from launch. The jobs
showed data freshness climbing with the wall clock, but only where at least one
partition of a topic was still getting records. If every partition of a topic was
pinned to the BoundedWindow.TIMESTAMP_MIN_VALUE, no chart showed at all. So the metric never pointed at the real problem —
it took per-partition logging to find.

Change

A new constructor taking advanceWatermarkBeforeFirstRecord. When true, check 3
is skipped, so a caught-up partition advances whether or not it has read
anything. A zero backlog means the reader is at the log end, so there's no unread
record that could turn up late.

Default is false, and the existing constructor passes false, so nothing changes
unless you ask for it.

Tests

  • testIdleWatermarkIsPinnedBeforeFirstRecordByDefault — default still returns
    TIMESTAMP_MIN_VALUE.
  • testIdleWatermarkAdvancesBeforeFirstRecordWhenEnabled — with the flag it
    advances to backlogCheckTime - maxDelay.
  • testCustomTimestampPolicyWithLimitedDelay — unchanged, still passes.

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: @Abacn for label java.
R: @Dippatel98 for label kafka.

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

Comment on lines 108 to 115
} else if (ctx.getMessageBacklog() == 0
&& ctx.getBacklogCheckTime().minus(maxDelay).isAfter(maxEventTimestamp) // Idle
&& maxEventTimestamp.getMillis() > 0) { // Read at least one record with positive timestamp.
&& ctx.getBacklogCheckTime().minus(maxDelay).isAfter(maxEventTimestamp)) { // Idle
// A zero backlog means the reader has a position and knows it is at the log end, so no
// unread record can arrive late regardless of whether one has ever been read. Requiring a
// record to have been read here as well would pin a partition which is caught up but has
// delivered nothing since the job started at 'maxEventTimestamp - maxDelay' forever, because
// only a delivered record can advance 'maxEventTimestamp'.
return ctx.getBacklogCheckTime().minus(maxDelay);

@sjvanrossum sjvanrossum Sep 20, 2026

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.

Unconditionally changing this may break existing users.
If a new partition is added or an existing partition is cleared before running a pipeline with the intent being to produce records to the partition after the pipeline is running and healthy, then there's a good reason to hold the watermark at TIMESTAMP_MIN_VALUE.

I'd consider making the proposed change configurable or splitting it out to a separate class instead of changing it unconditionally.

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.

After looking at this some more it seems like the intent was to advance the watermark unconditionally according to this comment.

// Watermark == maxEventTime - maxDelay, except in two special cases:
// a) maxEventTime in future : probably due to incorrect timestamps. Cap it to 'now'.
// b) partition is idle : Need to advance watermark if there are no records in the partition.
// We assume that future records will have timestamp >= 'now - maxDelay' and advance
// the watermark accordingly.
// The above handles majority of common use cases for custom timestamps. Users can implement
// their own policy if this does not work.

Still, this change will break users with an intentional or unintentional dependency on implemented instead of designed behavior. 😅

Note that ctx.getMessageBacklog() may return UnboundedReader.BACKLOG_UNKNOWN.

if (latestOffset < 0 || nextOffset < 0 || latestOffset < nextOffset) {
return UnboundedReader.BACKLOG_UNKNOWN;

The changes proposed in #39830 (port of ReadFromKafkaDoFn changes in #39285 to KafkaUnboundedReader) should make it less likely that the position gets ahead of the end offset (assuming that currentLag() is generally present after polling), because the end offset is no longer fetched by separate consumers and threads.

I'm wondering if it makes sense for this policy to also advance the watermark to backlog check time (last succeeded backlog check time?) when ctx.getMessageBacklog() <= 0 after the event time has advanced past BoundedWindow.TIMESTAMP_MIN_VALUE.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Hi @sjvanrossum , thanks for taking a look 🙇‍♂️ .

Pushed an update. It's opt-in constructor flag, default off, so nothing
changes for existing users. That should cover the "might break users" worry.

I also dropped the monotonicity clamp, which is where both your code suggestions
were, sorry about that. The reason: the watermark can already go backwards today.
Advance while idle, then a record arrives and you fall back to
maxEventTimestamp - maxDelay, which can be well behind the idle value. That's
existing behaviour with the gate in place, so fixing it felt like a separate
thing. The diff is now just the gate condition plus a constructor overload.

On BACKLOG_UNKNOWN: -1 fails == 0, so the watermark just holds. Safe, and
this PR doesn't change it.

On advancing at <= 0 — I'd keep that as a separate issue, since
BACKLOG_UNKNOWN means "I don't know if I'm caught up", which isn't the same as
== 0.

However, right now the flag is only reachable by building the policy yourself and
passing it through withTimestampPolicyFactory. I left it off from KafkaIO.Read to
keep this special behaviour away from default use cases.

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.

3 participants