[KafkaIO] Fix off-by-one message backlog in SDF read - #40016
Open
udayaw wants to merge 2 commits into
Open
Conversation
Contributor
|
Assigning reviewers: R: @chamikaramj for label java. Note: If you would like to opt out of this review, comment Available commands:
The PR bot will only process comments in the main thread (not review comments). |
uchathu
force-pushed
the
fix-off-by-one-backlog
branch
from
September 4, 2026 18:13
1e4fa20 to
d732b5b
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
ReadFromKafkaDoFnreports a fully caught-up partition as having a backlog of1, never 0. The cause is a collision between two offset conventions.
Kafka's offsets are exclusive; the tracker's claimed offset is not
Consumer#position()is documented as "the offset of the next record thatwill be fetched" — it is exclusive by design, not off by one.
currentLag()islogEndOffset - position(). So the estimate KafkaIO installs in the tracker,is exactly the log end offset — exclusive. That is precisely what the tracker
asks for;
GrowableOffsetRangeTracker.RangeEndEstimatorstates "The end offsetis exclusive for the range." The estimator is correct.
lastAttemptedOffset, however, is the last inclusive offset claimed. AndgetProgress()subtracts one from the other without converting:Once at least one record has been claimed,
workRemaining == realBacklog + 1(and
workCompletedis one short). Worked through, for a partition holdingoffsets 100–104 that the reader has fully drained:
position()currentLag()position + lag)lastAttemptedOffsetworkRemaining105 - 104= 1ReadFromKafkaDoFnthen feeds that straight to the timestamp policy:Why it matters
Both
CustomTimestampPolicyWithLimitedDelayandTimestampPolicyFactory.LogAppendTimePolicygate their idle-advance branch onctx.getMessageBacklog() == 0. Because that value can never reach zero, thebranch is unreachable, and an idle partition's watermark stays pinned at
lastRecordTimestamp - maxDelayfor as long as the partition stays quiet.Downstream event-time windows and triggers never fire.
Only the SDF path is affected.
KafkaUnboundedReader.backlogMessageCount()computes
latestOffset - nextOffset— exclusive minus exclusive — and does reach0. Dataflow always selects the SDF path (
KafkaIO.Read#runnerPrefersLegacyReadreturns false for any
org.apache.beam.runners.dataflow.*runner) unless theuse_deprecated_readexperiment is set, so pipelines there are exposed bydefault.
Observed in production on a Dataflow streaming job: a topic stopped producing and
the job reported data freshness growing 1:1 with wall clock for over eight hours,
while committed offsets showed the reader had been fully caught up the whole
time. It simply had no way to say so.
Evidence this is an oversight rather than intent
Two places in the existing code handle the exclusive/inclusive distinction
correctly, one of them three lines from the defect:
The claim path converts explicitly.
ReadFromKafkaDoFnsubtracts one fromposition()to obtain a claimable inclusive offset:The code knows the two conventions differ.
getProgress()just never convertsback.
The
backlogBytesgauge gets it right, ~20 lines belowupdateWatermarkManuallyin the same method, using the exclusiveexpectedOffset:Same method, two conventions, and the metric uses the correct one.
Notably, every offset in
processElementis already exclusive-next —tracker.currentRestriction().getFrom(),rawRecord.offset() + 1, andconsumer.position().lastAttemptedOffset, reachable only through the tracker,is the sole inclusive value in the picture.
Change
updateWatermarkManuallynow takes the exclusive next offset and the latest endoffset estimate directly, and computes
max(estimatedEndOffset, nextOffset) - nextOffset— exclusive minus exclusive,matching both the gauge and the legacy reader. Every call site already had
expectedOffsetin hand, so no new state is threaded through.TimestampPolicy.PartitionContext#getMessageBacklog's javadoc previously read"latest offset of the partition - last processed record offset", which
describes the buggy inclusive arithmetic and is plausibly how the slip survived
review. Reworded to state that both offsets are exclusive and that zero means
fully caught up.
Long.MIN_VALUE— the sentinellatestOffsetEstimatorholds when the position isundefined or out of range — still yields a backlog of 0 via the
max, matchingtoday's behaviour on that path.
Compacted topics
The value this method reports is a count of offsets, not of messages —
compaction deletes records while leaving the offset span intact, so on a
compacted topic the backlog overstates how many records actually remain. That is
pre-existing and unchanged here;
getSizealready notes it ("Compacted topicsmay hold less records than the estimated offset range due to record deletion
within a partition"), and the legacy
KafkaUnboundedReaderhas the samecharacteristic since it also computes
latestOffset - nextOffset. This changeremoves a systematic off-by-one that affects every topic, compacted or not.
The idle-advance path does still reach zero on a compacted topic. The
"non-visible progress" branch claims up to
consumer.position() - 1whenever theposition advances without any records being returned, which is exactly what a
fetch across a compacted region looks like, so
expectedOffsetfollows theconsumer past the gaps. For a partition whose surviving records are at offsets
0, 2 and 4 with a log end offset of 5, the backlog after the final record is 0
with this change and 1 without it.
What this change does not address is a consumer position that stalls below the
log end offset with nothing left to fetch; the backlog would stay positive and
the watermark would not advance. That is a fetch-position concern rather than an
arithmetic one, is unaffected by this change, and behaves identically on the
legacy read path.
Alternative considered: converting inside the tracker
The root cause is in
GrowableOffsetRangeTracker.getProgress(), andcompletedEnd = lastAttemptedOffset + 1would fixworkCompletedtoo. I did notdo that here because:
consume those for splitting and autoscaling decisions;
lastAttemptedOffset == Long.MAX_VALUE(range done) case, since
getProgressfeeds the subtraction throughUnsignedLong.fromLongBits.The two fixes are independent — this one derives the backlog without consulting
the tracker — so a later tracker fix will not double-correct. Happy to switch to
it, or file it as a follow-up, if reviewers prefer.
Scope note:
getSize()is not affected. It builds a fresh tracker percall, so
lastAttemptedOffsetis null,completedEnd == range.getFrom(), andworkRemaining == estimate - from— correct, because restriction starts areexclusive-next offsets. The in-flight
getProgress()the runner queries duringbundle processing does stay off by one until the tracker itself is fixed; that
affects splitting and progress reporting, not watermarks.
Tests
Four tests in
ReadFromKafkaDoFnTest, all driving the realGrowableOffsetRangeTrackerthroughrestrictionTracker():testMessageBacklogReachesZeroWhenPartitionIsCaughtUp— exact backlog sequence[2, 1, 0, 0]for three records on a partition with end offset 3.testMessageBacklogExcludesRecordsAlreadyRead—[7, 6, 5, 5]with fiverecords left unread.
testWatermarkAdvancesForIdleCaughtUpPartition— a realCustomTimestampPolicyWithLimitedDelayadvances past the last record'stimestamp once the partition drains.
testWatermarkDoesNotAdvanceForIdlePartitionWithBacklog— the same policystays at
lastRecordTimestamp - maxDelaywhile records remain.All four fail before the change and pass after. They use a new
IdlingMockKafkaConsumer, which returns one batch then empty polls and trackspositionsocurrentLagis meaningful; the existingSimpleMockKafkaConsumerreturns a fixed
positionand cannot express "caught up".Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:
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, commentfixes #<ISSUE NUMBER>instead.CHANGES.mdwith noteworthy changes.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)
See CI.md for more information about GitHub Actions CI or the workflows README to see a list of phrases to trigger workflows.