Repository navigation
[JmsIO] Acknowledge messages of checkpoints that are never finalized - #41013
Conversation
There was a problem hiding this comment.
📋 Review Summary
This PR resolves a critical bug where UnboundedSourceAsSDFRestrictionTracker.getProgress() invoked getCheckpointMark(), causing JmsIO (and potentially other stateful unbounded sources) to create orphaned checkpoints that were never finalized. The core fix in Read.java avoids taking checkpoints during progress checks, and the defense-in-depth changes in JmsIO track per-reader checkpoint sequences so that finalizing or resuming from a checkpoint also acknowledges any earlier unfinalized checkpoints.
🔍 General Feedback
- The root cause analysis and two-pronged fix (in
Read.javaandJmsIO) are very well thought out, clean, and thoroughly tested. - Thread-safety, serialization compatibility (
serialVersionUID), and resource cleanup oncloseTimeoutare all properly handled.
💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.
| * (Python) RunInference now measures model memory (the `model_byte_size` metric) when `torch` is not installed. It was always 0, because a failed `ModelManager` import also disabled the `resource` module ([#40854](https://github.com/apache/beam/issues/40854)). | ||
| * (Python) Fixed `GeminiModelHandler` returning only one result per batch: each prompt is now sent as its own request (up to 32 at a time), so every input gets its own result. A custom `request_fn` must now return one response per input ([#40913](https://github.com/apache/beam/issues/40913)). | ||
| * (Java) BigQuery Storage Write API successful-row output now propagates fused downstream exceptions instead of allowing the bundle to succeed with missing downstream results ([#40004](https://github.com/apache/beam/pull/40004)). | ||
| * (Java) Fixed JmsIO leaving most messages unacknowledged, and so redelivered, on runners that execute unbounded sources as splittable DoFns, such as Dataflow Runner v2. Reporting progress for an unbounded source no longer takes a checkpoint, and finalizing a JmsIO checkpoint, or resuming from it, also acknowledges the earlier checkpoints of the same reader. |
There was a problem hiding this comment.
🟢 Nit: Consider adding the PR reference (([#41013](https://github.com/apache/beam/pull/41013))) at the end of the CHANGES.md entry to match the convention of the surrounding entries.
| * (Java) Fixed JmsIO leaving most messages unacknowledged, and so redelivered, on runners that execute unbounded sources as splittable DoFns, such as Dataflow Runner v2. Reporting progress for an unbounded source no longer takes a checkpoint, and finalizing a JmsIO checkpoint, or resuming from it, also acknowledges the earlier checkpoints of the same reader. | |
| * (Java) Fixed JmsIO leaving most messages unacknowledged, and so redelivered, on runners that execute unbounded sources as splittable DoFns, such as Dataflow Runner v2. Reporting progress for an unbounded source no longer takes a checkpoint, and finalizing a JmsIO checkpoint, or resuming from it, also acknowledges the earlier checkpoints of the same reader ([#41013](https://github.com/apache/beam/pull/41013)). |
|
Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment |
|
Assigning reviewers: R: @damccorm for label java. This pull request likely touches a core component ("core" label). Please review with scrutiny. 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). |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #41013 +/- ##
=========================================
Coverage 58.36% 58.36%
Complexity 2277 2277
=========================================
Files 1136 1136
Lines 169341 169341
Branches 1482 1482
=========================================
Hits 98838 98838
Misses 67952 67952
Partials 2551 2551 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
Thanks! Since it touches core path (Read.java), would you mind triggering PostCommit Dataflow v2 tests, that is to push a change modifying https://github.com/apache/beam/blob/master/.github/trigger_files/beam_PostCommit_Java_Examples_Dataflow_V2.json |
|
@Abacn done, thanks! |
There was a problem hiding this comment.
Thanks for tracking this down @jbonofre — great root-cause analysis!
A few high-level thoughts and questions:
-
Impact on other
UnboundedSourceIOs (AI helped me find these :)): The core fix inRead.java(UnboundedSourceAsSDFRestrictionTracker.getProgress()no longer callingcurrentRestriction()->getCheckpointMark()) actually fixes silent bugs in several otherUnboundedSourceconnectors when executed as an SDF (e.g., on Dataflow Runner v2):MqttIO:MqttCheckpointMark.Preparer.newCheckpoint()drainsmessagesinto the returnedMqttCheckpointMarkand resetsmessages = new ArrayList<>()(identical toJmsIO), so everygetProgress()call was dropping MQTT acks.SolaceIO(UnboundedSolaceReader):getCheckpointMark()copies and clearsreceivedMessagesinto a newPendingCheckpointkeyed bycheckpointId. BecauseSolaceCheckpointMark.finalizeCheckpoint()only acks its owncheckpointId, everygetProgress()call was orphaning messages inpendingCheckpoints.SqsUnboundedReaderandPubsubUnboundedSource: Both incrementnumInFlightCheckpointson everygetCheckpointMark()call and only decrement it infinalizeCheckpoint()(which gates closing the SQS client / PubSub reader), so discarded checkpoints fromgetProgress()permanently leakednumInFlightCheckpoints.UnboundedReadFromBoundedSource:getCheckpointMark()splits the underlyingresidualSourceand re-initializes the reader on every call.
-
Splitting the PR: Because the
Read.java(sdks/java/core) changes have broad impact across allUnboundedSourceIOs beyondJmsIO, could you split this PR into 2 PRs — one for the coreRead.java/ReadTest.javafix and one for theJmsIO-specific changes? That will make both easier to understand/review. Particularly since theRead.javapieces are central and have broader impact, it would be nice to handle those independently of just JMS. -
Dataflow verification: Were you able to run a streaming job on Dataflow before and after these changes to confirm the difference in acknowledgment/consumer behavior?
| private boolean isDone() { | ||
| @Nullable UnboundedReader<OutputT> reader = currentReader; | ||
| if (reader == null || !readerHasBeenStarted) { | ||
| return initialRestriction.getSource() instanceof EmptyUnboundedSource; | ||
| } | ||
| return reader instanceof EmptyUnboundedSource.EmptyUnboundedReader | ||
| || BoundedWindow.TIMESTAMP_MAX_VALUE.equals( | ||
| ensureTimestampWithinBounds(reader.getWatermark())); | ||
| } |
There was a problem hiding this comment.
While removing currentRestriction() from tryGetProgressOrThrow() eliminates the mid-bundle progress checkpoints, UnboundedSourceAsSDFWrapperFn.processElement still calls currentRestriction() -> currentReader.getCheckpointMark() 3 times at the end of every bundle where start() or advance() returns false (out[0] == null, so currentReader is not yet an EmptyUnboundedReader):
- Line 610:
UnboundedSourceRestriction<OutputT, CheckpointT> currentRestriction = tracker.currentRestriction();takes Checkpoint 1 and registerscheckpoint::finalizeCheckpointwithbundleFinalizer.afterBundleCommit(...). - Line 620:
&& !(tracker.currentRestriction().getCheckpoint() instanceof NoopCheckpointMark)callstracker.currentRestriction()a second time instead of checking the local variable!(checkpoint instanceof NoopCheckpointMark)from line 617, taking Checkpoint 2 and immediately dropping it. - Line 636 (
ProcessContinuation.resume()): ReturningProcessContinuation.resume()causes the runner/harness (FnApiDoFnRunner/OutputAndTimeBoundedSplittableProcessElementInvoker) to immediately invoketracker.trySplit(0), which at line 1035 callscurrentRestriction()a third time (Checkpoint 3).
Because Checkpoint 1 at line 610 already drained stateful checkpoint preparers (like JmsIO, MqttIO, SolaceIO), Checkpoint 2 is dropped and Checkpoint 3 (which is returned in SplitResult as the residual restriction to the runner and used as the cachedReaders cache key!) is a different, empty checkpoint whose oldestMessageTimestamp in JmsIO/MqttIO was reset to Instant.now().
In the core Read.java PR, could we at minimum replace !(tracker.currentRestriction().getCheckpoint() instanceof NoopCheckpointMark) at line 620 with !(checkpoint instanceof NoopCheckpointMark), and ideally avoid taking separate checkpoints at line 610 and inside trySplit(0) when the bundle ends with ProcessContinuation.resume()?
|
Sorry for being late. This LGTM and I'm fine with current form or split it if you prefer. PostCommit Dataflow v2 should already have verified its not breaking existing IO (GCP ones at least) |
All these IOs are backed by UnboundedSource so yeah technical they have same bug A good followup (not in scope of this PR) is to check if Python UnboundedSource (added recently) has similar issue |
Yeah - I was mostly curious if other IOs specifically would run into this particular issue (they do), and that was helpful context for deciding if the other comments mattered.
I am not really worried about it breaking other IOs, and I do think this is a net positive. I think it maybe misses other potential issues though and we might need slightly broader changes to Specifically, we call currentRestriction 3 times, starting here -
So bundleFinalizer gets Checkpoint 1, Checkpoint 2 gets dropped, and the runner persists Checkpoint 3. Checkpoints 2 and 3 are likely empty, which is ok for JmsIO with these changes, but problematic for other IOs. As examples: SqsUnboundedReader and PubsubUnboundedSource don't clear their safeToDeleteIds / safeToAckIds until finalizeCheckpoint(), and they unconditionally call numInFlightCheckpoints.incrementAndGet() on every getCheckpointMark() call. Because Checkpoints 2 and 3 are never registered with bundleFinalizer, numInFlightCheckpoints never drops back to 0 (which prevents cleanup from happening). |
|
I'm fine not splitting the PR up though - I guess we've already done most of the authoring/review work at this point as is. Mostly, it would just be good to swap to!(checkpoint instanceof NoopCheckpointMark) to avoid running the checkpoint an extra time and more fully fix the issue.
|
|
Regardless, I'll defer to you here @Abacn |
|
@Abacn @damccorm by the way, I worked with a Dataflow user on this one, and the user confirmed that this PR fixes the issue with Dataflow. The user created a Beam pipeline that consumes from ActiveMQ (with the JmsIO), do transform, and produce to Kafka (with KafkaIO). |
|
Sounds good to me - would you be ok making the change in #41013 (comment) and resolving conflicts? I think at that point, I'm good to merge this as well. |
|
@damccorm sure! No problem at all. Let me do that 😄 |
UnboundedSourceAsSDFRestrictionTracker.getProgress() called currentRestriction(), which calls getCheckpointMark() on the reader. A checkpoint ends the bundle of elements read so far (see UnboundedReader#getCheckpointMark()), and the one taken for progress was dropped, so it was never committed nor finalized. Sources whose checkpoint holds state, such as JmsIO, then never acknowledged the messages read before the last progress request. Check whether the tracker is done without taking a checkpoint.
…r resuming from one A runner commits a checkpoint only once all earlier checkpoints of the same reader are committed, so finalizing a checkpoint now also acknowledges the earlier checkpoints of that reader that are not finalized. This covers checkpoints that are taken but never committed, such as the ones Beam's SDF wrapper took to report progress before the previous commit, and checkpoints whose finalize callback is lost. Resuming a reader from a checkpoint acknowledges it too when the reader that took it lives in this JVM, since a runner resumes only from committed checkpoints. The per-checkpoint registry becomes a per-reader one: a checkpoint carries its reader id and sequence instead of a random id. When the connection closes after closeTimeout, the checkpoints still pending are dropped, and an INFO line reports how many messages the broker will redeliver. Add DEBUG logs for readers, checkpoints and finalization.
…oundedSourceAsSDFWrapperFn.processElement
d690fab to
2987da6
Compare
|
@Abacn thanks! Let me open the PR for the other IOs. |
|
Sorry, I understand the fixes in Read.java is generic and fixes high rate of unfinalized checkpoints for all IOs using UnboundedSource By saying "open the PR for the other IOs" does it mean all IOs needs modification after this PR? (If so it's a breaking change we may need reconsider) Or just quality-of-life improvements (preserving info of pending commits after serialization-deserialization)? |
On runners that execute unbounded sources as splittable DoFns, such as Dataflow Runner v2, JmsIO acknowledges only a small fraction of the messages it reads. The rest are redelivered and processed again.
Cause
UnboundedSourceAsSDFRestrictionTracker.getProgress()callscurrentRestriction(), which callsgetCheckpointMark()on the live reader. The SDK harness callsgetProgress()on every progress request during a bundle.For JmsIO,
getCheckpointMark()is not a snapshot. It moves the messages read so far into a new checkpoint, gives that checkpoint the current session and consumer, and opens new ones. The progress code drops that checkpoint, so it is never finalized. Only the messages read after the last progress request get acknowledged.The dropped checkpoints also keep their session and consumer open until the reader's connection closes after
closeTimeout. The broker then redelivers their messages.This matches what we saw on a Dataflow streaming job (CLIENT_ACKNOWLEDGE,
withRequiresDeduping()):#40605 did not change this, because Dataflow finalizes the in-memory checkpoint, never a restored copy. We have not yet confirmed that this job runs on Runner v2; the DEBUG logs below will show it.
Changes
Core (
Read.java): progress reporting no longer callsgetCheckpointMark(). It checks for the empty reader or the maximum watermark directly.UnboundedReader#getCheckpointMark()documents that the elements read between two calls form one bundle, so it must not be called only to report progress.JmsIO:
createReader(options, checkpoint)acknowledges the checkpoint it resumes from, and the earlier ones, when the reader that took it lives in this JVM. A runner resumes only from committed checkpoints; the direct runner already finalizes a checkpoint when it resumes from it. This replaces the per-checkpoint registry of [JmsIO] Let restored checkpoint marks acknowledge live messages #40605 with a per-reader one: a checkpoint now carries its reader id and a sequence number instead of a random id. As a result, an empty checkpoint can also acknowledge the earlier ones.closeTimeoutwith checkpoints still pending, those checkpoints are dropped instead of being acknowledged later on a closed connection. An INFO line reports how many messages the broker will redeliver.--sdkHarnessLogLevelOverrides={"org.apache.beam.sdk.io.jms":"DEBUG"}on Runner v2, or--workerLogLevelOverrideson the legacy Dataflow worker.Compatibility
Checkpoints written by released versions still decode, since
serialVersionUIDis unchanged. They carry no reader id, so there is nothing to acknowledge after restoring them, as before. Theidfield from #40605 was never in a release.Tests
ReadTest: progress no longer takes a checkpoint, whiletrySplitstill does. This test fails without the core change.JmsLocalTest:closeTimeoutdrops pending checkpoints.JmsIOTest(embedded broker, ActiveMQ and Qpid clients):