damccorm commented on code in PR #41704:
URL: https://github.com/apache/beam/pull/41704#discussion_r4744099070
##########
sdks/java/core/src/main/java/org/apache/beam/sdk/io/Read.java:
##########
@@ -595,45 +616,60 @@ public ProcessContinuation processElement(
OutputReceiver<ValueWithRecordId<OutputT>> receiver,
BundleFinalizer bundleFinalizer)
throws IOException {
- UnboundedSourceRestriction<OutputT, CheckpointT> initialRestriction =
- tracker.currentRestriction();
-
- @SuppressWarnings("rawtypes") // most straightforward way to create
array with type parameter
- UnboundedSourceValue<OutputT>[] out = new UnboundedSourceValue[1];
- while (tracker.tryClaim(out) && out[0] != null) {
- watermarkEstimator.setWatermark(out[0].getWatermark());
- receiver.outputWithTimestamp(
- new ValueWithRecordId<>(out[0].getValue(), out[0].getId()),
out[0].getTimestamp());
+ if (tracker instanceof UnboundedSourceAsSDFRestrictionTracker) {
+ currentTracker = (UnboundedSourceAsSDFRestrictionTracker<OutputT,
CheckpointT>) tracker;
+ } else {
+ currentTracker = null;
}
+ try {
+ UnboundedSourceRestriction<OutputT, CheckpointT> initialRestriction =
+ tracker.currentRestriction();
+
+ @SuppressWarnings(
+ "rawtypes") // most straightforward way to create array with type
parameter
+ UnboundedSourceValue<OutputT>[] out = new UnboundedSourceValue[1];
+ while (tracker.tryClaim(out) && out[0] != null) {
+ watermarkEstimator.setWatermark(out[0].getWatermark());
+ receiver.outputWithTimestamp(
+ new ValueWithRecordId<>(out[0].getValue(), out[0].getId()),
out[0].getTimestamp());
+ }
- UnboundedSourceRestriction<OutputT, CheckpointT> currentRestriction =
- tracker.currentRestriction();
-
- // Add the checkpoint mark to be finalized if the checkpoint mark isn't
trivial and is not
- // the initial restriction. The initial restriction would have been
finalized as part of
- // a prior bundle being executed.
- @SuppressWarnings("ReferenceEquality")
- boolean isInitialRestriction = initialRestriction == currentRestriction;
- CheckpointT checkpoint = currentRestriction.getCheckpoint();
- if (checkpoint != null
- && !isInitialRestriction
- && !(checkpoint instanceof NoopCheckpointMark)) {
- bundleFinalizer.afterBundleCommit(
-
Instant.now().plus(Duration.standardMinutes(DEFAULT_BUNDLE_FINALIZATION_LIMIT_MINS)),
- checkpoint::finalizeCheckpoint);
- }
+ UnboundedSourceRestriction<OutputT, CheckpointT> currentRestriction =
+ tracker.currentRestriction();
+
+ // Add the checkpoint mark to be finalized if the checkpoint mark
isn't trivial and is not
+ // the initial restriction. The initial restriction would have been
finalized as part of
+ // a prior bundle being executed.
+ @SuppressWarnings("ReferenceEquality")
+ boolean isInitialRestriction = initialRestriction ==
currentRestriction;
+ CheckpointT checkpoint = currentRestriction.getCheckpoint();
+ if (checkpoint != null
+ && !isInitialRestriction
+ && !(checkpoint instanceof NoopCheckpointMark)) {
+ bundleFinalizer.afterBundleCommit(
+
Instant.now().plus(Duration.standardMinutes(DEFAULT_BUNDLE_FINALIZATION_LIMIT_MINS)),
+ checkpoint::finalizeCheckpoint);
+ }
- // If we have been split/checkpoint by a runner, the tracker will have
been updated to the
- // empty source and we will return stop. Otherwise the unbounded source
has only temporarily
- // run out of work.
- if (currentRestriction.getSource() instanceof EmptyUnboundedSource) {
- return ProcessContinuation.stop();
- }
+ // If we have been split/checkpoint by a runner, the tracker will have
been updated to the
+ // empty source and we will return stop. Otherwise the unbounded
source has only temporarily
+ // run out of work.
+ if (currentRestriction.getSource() instanceof EmptyUnboundedSource) {
+ return ProcessContinuation.stop();
+ }
- // Advance the watermark even if zero elements may have been output.
Only report it if we
- // are resuming.
- watermarkEstimator.setWatermark(currentRestriction.getWatermark());
- return ProcessContinuation.resume();
+ // Advance the watermark even if zero elements may have been output.
Only report it if we
+ // are resuming.
+ watermarkEstimator.setWatermark(currentRestriction.getWatermark());
+ return ProcessContinuation.resume();
+ } catch (Throwable t) {
+ if (currentTracker != null) {
+ currentTracker.closeCurrentReader(t);
Review Comment:
Calling `currentTracker.closeCurrentReader(t)` directly from
`processElement`'s `catch` block bypasses `RestrictionTrackers.observe`'s
`ReentrantLock`. In `FnApiDoFnRunner` (and
`OutputAndTimeBoundedSplittableProcessElementInvoker`), `trySplit()` and
`getProgress()` can run concurrently on another thread while
`receiver.outputWithTimestamp(...)` is executing outside that lock. Because
`currentReader`, `readerHasBeenStarted`, and `lastRestriction` are non-volatile
and unsynchronized, `closeCurrentReader` can race with `trySplit()` (calling
`close()` concurrently with `getCheckpointMark()`/`getWatermark()`, or closing
a reader that `trySplit()` just placed into `cachedReaders` — causing a failure
on reuse and a double-`close()` on eviction).
Also, `closeCurrentReader` sets `currentReader = null` without resetting
`readerHasBeenStarted = false` (or marking the tracker closed). If a concurrent
`getProgress()` runs right after `closeCurrentReader` before the bundle fails,
`tryGetProgressOrThrow()` will call `initializeCurrentReader()` to open a fresh
reader and cache it with `isStarted = true` even though `start()` was never
called (and a concurrent `trySplit()` can return a bogus split with
`initialRestriction`).
Synchronizing `tryClaim`, `currentRestriction`, `trySplit`, `checkDone`,
`getProgress`, and `closeCurrentReader` on
`UnboundedSourceAsSDFRestrictionTracker` (strictly inside
`RestrictionTrackerObserver.lock`, so no deadlock risk) and resetting
`readerHasBeenStarted = false` / setting a `closed` flag in
`closeCurrentReader` should close both holes cleanly.
##########
sdks/java/core/src/main/java/org/apache/beam/sdk/io/Read.java:
##########
@@ -934,29 +1080,51 @@ private void cacheCurrentReader(
cachedReaders.put(
createCacheKey(restriction.getSource(),
restriction.getCheckpoint()),
CacheState.create(reader, readerHasBeenStarted));
+ scheduleCacheCleanUp(cachedReaders);
+ }
+ }
+
+ void closeCurrentReader(@Nullable Throwable exception) {
+ lastRestriction = null;
+ if (this.currentReader != null) {
+ try {
+ currentReader.close();
+ } catch (IOException closeException) {
Review Comment:
Since the callers now catch `Throwable`, should `closeCurrentReader` also
catch `Throwable` (like `try-with-resources`) rather than only `IOException`?
If a broken reader throws a `RuntimeException` (e.g. `IllegalStateException` /
`JMSRuntimeException` / `KafkaException`) from `close()`, it will currently
mask the original exception `t` instead of being attached via `addSuppressed`.
##########
sdks/java/core/src/main/java/org/apache/beam/sdk/io/Read.java:
##########
@@ -989,27 +1157,44 @@ public UnboundedSourceRestriction<OutputT, CheckpointT>
currentRestriction() {
if (currentReader == null || !readerHasBeenStarted) {
return initialRestriction;
}
- UnboundedReader<OutputT> currentReader = this.currentReader;
- Instant watermark =
ensureTimestampWithinBounds(currentReader.getWatermark());
- // We convert the reader to the empty reader to mark that we are done.
- if (!(currentReader instanceof
EmptyUnboundedSource.EmptyUnboundedReader)
- && BoundedWindow.TIMESTAMP_MAX_VALUE.equals(watermark)) {
- CheckpointT checkpointT = (CheckpointT)
currentReader.getCheckpointMark();
- try {
- currentReader.close();
- } catch (IOException e) {
- LOG.warn("Failed to close UnboundedReader.", e);
- } finally {
- this.currentReader =
- EmptyUnboundedSource.INSTANCE.createReader(
- PipelineOptionsFactory.create(), checkpointT);
+ if (lastRestriction != null) {
+ return lastRestriction;
+ }
+ try {
+ UnboundedReader<OutputT> currentReader = this.currentReader;
+ Instant watermark =
ensureTimestampWithinBounds(currentReader.getWatermark());
+ // We convert the reader to the empty reader to mark that we are
done.
+ if (!(currentReader instanceof
EmptyUnboundedSource.EmptyUnboundedReader)
+ && BoundedWindow.TIMESTAMP_MAX_VALUE.equals(watermark)) {
+ CheckpointT checkpointT = (CheckpointT)
currentReader.getCheckpointMark();
+ try {
+ currentReader.close();
+ } catch (IOException e) {
+ LOG.warn("Failed to close UnboundedReader.", e);
+ } finally {
+ this.currentReader =
+ EmptyUnboundedSource.INSTANCE.createReader(
+ PipelineOptionsFactory.create(), checkpointT);
+ }
+ return UnboundedSourceRestriction.create(
+ (UnboundedSource<OutputT, CheckpointT>)
currentReader.getCurrentSource(),
Review Comment:
Minor nit: `currentReader` here is the shadowed local variable holding the
just-closed reader rather than `this.currentReader`. Capturing
`currentReader.getCurrentSource()` before calling `currentReader.close()`
avoids calling a method on a closed reader while preserving the existing
watermark/`resume()` behavior.
##########
sdks/java/core/src/main/java/org/apache/beam/sdk/io/Read.java:
##########
@@ -1052,6 +1237,7 @@ private boolean isDone() {
currentRestriction);
cacheCurrentReader(currentRestriction);
Review Comment:
Once `processElement` returns `resume()`, its `finally` block has already
cleared `currentTracker = null`. If `cacheCurrentReader(currentRestriction)`
throws during the runner's subsequent `trySplit(0)` (e.g.
`checkpointCoder.encode` fails inside `structuralValue`), `currentReader` will
leak. Wrapping `trySplit` in `try { ... } catch (Throwable t) {
closeCurrentReader(t); throw rethrow(t); }` would keep it consistent with
`tryClaim`, `currentRestriction`, and `getProgress`.
##########
CHANGES.md:
##########
@@ -196,6 +196,7 @@
* (Python) Fixed `GroupByKey`, `CombinePerKey`, `Distinct` and stateful DoFns
failing with "Unable to deterministically encode" on `datetime.date`,
`datetime.timedelta` and naive or UTC `datetime.datetime` keys
([#21034](https://github.com/apache/beam/issues/21034)).
* (Python) Fixed file-based sinks such as `WriteToText` treating glob
characters in the output path as a pattern: a path such as `out[12]` deleted
other files that the pattern matched and then failed to finalize
([#41567](https://github.com/apache/beam/issues/41567)).
* (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)).
+* (Java) Fixed `UnboundedSource` splittable DoFn execution recreating readers
on every bundle when the source's Java serialization output changes across
round trips (such as `JmsIO` with `ActiveMQConnectionFactory`), taking a
duplicate checkpoint when `processElement` returns `resume()`, and leaving
readers open when bundle processing fails
([#41704](https://github.com/apache/beam/pull/41704)).
Review Comment:
Heads-up: this branch also picked up a merge conflict with `master` (likely
here in `CHANGES.md`).
##########
sdks/java/core/src/main/java/org/apache/beam/sdk/io/Read.java:
##########
@@ -877,23 +994,51 @@ private static class
UnboundedSourceAsSDFRestrictionTracker<
extends RestrictionTracker<
UnboundedSourceRestriction<OutputT, CheckpointT>,
UnboundedSourceValue<OutputT>[]>
implements HasProgress {
+ private static final Set<Cache<Object, ?>>
CACHES_WITH_SCHEDULED_CLEAN_UP =
+ ConcurrentHashMap.newKeySet();
+
private final UnboundedSourceRestriction<OutputT, CheckpointT>
initialRestriction;
private final PipelineOptions pipelineOptions;
private final Cache<Object, CacheState<OutputT>> cachedReaders;
private final Coder<UnboundedSourceRestriction<OutputT, CheckpointT>>
restrictionCoder;
+ private final Consumer<UnboundedSourceAsSDFRestrictionTracker<OutputT,
CheckpointT>>
+ onClaimCallback;
private UnboundedSource.@Nullable UnboundedReader<OutputT> currentReader;
private boolean readerHasBeenStarted;
+ private @Nullable UnboundedSourceRestriction<OutputT, CheckpointT>
lastRestriction;
UnboundedSourceAsSDFRestrictionTracker(
UnboundedSourceRestriction<OutputT, CheckpointT> initialRestriction,
PipelineOptions pipelineOptions,
Cache<Object, CacheState<OutputT>> cachedReaders,
- Coder<UnboundedSourceRestriction<OutputT, CheckpointT>>
restrictionCoder) {
+ Coder<UnboundedSourceRestriction<OutputT, CheckpointT>>
restrictionCoder,
+ Consumer<UnboundedSourceAsSDFRestrictionTracker<OutputT,
CheckpointT>> onClaimCallback) {
this.initialRestriction = initialRestriction;
this.pipelineOptions = pipelineOptions;
this.cachedReaders = cachedReaders;
this.restrictionCoder = restrictionCoder;
+ this.onClaimCallback = onClaimCallback;
+ }
+
+ private static void scheduleCacheCleanUp(Cache<Object, ?> cachedReaders)
{
+ if (CACHES_WITH_SCHEDULED_CLEAN_UP.add(cachedReaders)) {
+ @SuppressWarnings("FutureReturnValueIgnored")
+ Object unused =
+ cacheCleanUpExecutor.schedule(
+ () -> {
+ try {
+ cachedReaders.cleanUp();
Review Comment:
Nit: since the `ScheduledFuture` is ignored, any unchecked exception from
`cachedReaders.cleanUp()` will be dropped without logging. Worth catching and
logging with `LOG.warn` inside the scheduled runnable. (Note: the bot's earlier
comment about `remove` vs `size` ordering was mistaken — `remove` is already
before `size()`.)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]