damccorm commented on code in PR #41506:
URL: https://github.com/apache/beam/pull/41506#discussion_r4787856996
##########
sdks/java/io/amazon-web-services2/src/main/java/org/apache/beam/sdk/io/aws2/sqs/SqsUnboundedSource.java:
##########
@@ -50,6 +50,16 @@ public List<SqsUnboundedSource> split(int desiredNumSplits,
PipelineOptions opti
@Override
public UnboundedReader<SqsMessage> createReader(
PipelineOptions options, @Nullable SqsCheckpointMark checkpointMark) {
+ if (checkpointMark != null) {
+ try {
+ // A runner resumes from a checkpoint only once it is committed, so
its messages can be
+ // deleted if the reader that took it lives in this JVM.
+ checkpointMark.finalizeCheckpoint();
+ } catch (IOException e) {
+ throw new RuntimeException(
+ "Unable to finalize resumed checkpoint for " + read.queueUrl() +
": ", e);
+ }
+ }
Review Comment:
Checkpoint finalization is best-effort
(`SqsUnboundedSource.requiresDeduping()` is `true`), and if a runner is
recreating the reader because the previous reader's `sqsClient` hit an error
(while still within the 60s close timeout), throwing `RuntimeException` here
will abort recovery and skip
`expireBatchForRedelivery(checkpointMark.notYetReadReceipts)`.
Could we catch `IOException` (and ideally `RuntimeException` from AWS SDK
calls, or `Exception`) and log a warning instead of failing `createReader()`,
matching `JmsIO`'s non-fatal behavior?
##########
sdks/java/io/amazon-web-services2/src/main/java/org/apache/beam/sdk/io/aws2/sqs/SqsCheckpointMark.java:
##########
@@ -68,32 +88,150 @@ class SqsCheckpointMark implements
UnboundedSource.CheckpointMark, Serializable
SqsUnboundedReader reader,
Collection<String> messagesToDelete,
Collection<String> notYetReadReceipts) {
+ this(null, 0, reader, messagesToDelete, notYetReadReceipts);
+ }
+
+ SqsCheckpointMark(
+ @Nullable PendingCheckpoints pendingCheckpoints,
+ long sequence,
+ SqsUnboundedReader reader,
+ Collection<String> messagesToDelete,
+ Collection<String> notYetReadReceipts) {
+ this.pendingCheckpoints = pendingCheckpoints;
+ this.readerId = pendingCheckpoints == null ? null :
pendingCheckpoints.readerId;
+ this.sequence = sequence;
this.reader = Optional.of(reader);
this.safeToDeleteIds = ImmutableList.copyOf(messagesToDelete);
this.notYetReadReceipts = ImmutableList.copyOf(notYetReadReceipts);
}
@Override
public void finalizeCheckpoint() throws IOException {
- checkState(
- reader.isPresent() && safeToDeleteIds != null, "Cannot finalize a
restored checkpoint");
+ PendingCheckpoints pending = pendingCheckpoints;
+ if (pending == null && readerId != null) {
+ pending = PendingCheckpoints.LIVE.getIfPresent(readerId);
+ }
+ if (pending != null) {
+ List<SqsCheckpointMark> checkpoints = pending.removeUpTo(sequence);
+ if (checkpoints.isEmpty()) {
+ return;
+ }
+ Set<String> toDelete = new LinkedHashSet<>();
+ for (SqsCheckpointMark checkpoint : checkpoints) {
+ if (checkpoint.safeToDeleteIds != null) {
+ toDelete.addAll(checkpoint.safeToDeleteIds);
+ }
+ }
+ try {
+ pending.reader.delete(new ArrayList<>(toDelete));
+ } finally {
+ for (SqsCheckpointMark checkpoint : checkpoints) {
+ checkpoint.clearAndDecrement();
+ }
+ pending.reader.maybeCloseClient();
+ }
+ return;
+ }
+
+ if (reader == null || !reader.isPresent()) {
+ LOG.debug(
+ "Finalized checkpoint {}#{}: its reader is not in this JVM, nothing
to acknowledge",
+ readerId,
+ sequence);
+ return;
+ }
+
+ checkState(safeToDeleteIds != null, "Cannot finalize an already finalized
checkpoint");
// Even if the 'true' active reader has changed since the checkpoint was
taken we are
// fine:
// - The underlying SQS topic will not have changed, so the following
deletes will still
// go to the right place.
// - We'll delete the ACK ids from the readers in-flight state, but that
only affect
// flow control and stats, neither of which are relevant anymore.
+ SqsUnboundedReader liveReader = reader.get();
try {
- reader.get().delete(safeToDeleteIds);
+ liveReader.delete(safeToDeleteIds);
} finally {
- int remainingInFlight =
reader.get().numInFlightCheckpoints.decrementAndGet();
- checkState(remainingInFlight >= 0, "Miscounted in-flight checkpoints");
- reader.get().maybeCloseClient();
+ clearAndDecrement(liveReader);
+ liveReader.maybeCloseClient();
+ }
+ }
+
+ private void clearAndDecrement() {
+ SqsUnboundedReader liveReader =
+ pendingCheckpoints != null
+ ? pendingCheckpoints.reader
+ : (reader != null && reader.isPresent() ? reader.get() : null);
+ if (liveReader != null) {
+ clearAndDecrement(liveReader);
+ } else {
reader = Optional.empty();
safeToDeleteIds = null;
}
}
+ private synchronized void clearAndDecrement(SqsUnboundedReader liveReader) {
+ if (safeToDeleteIds == null && (reader == null || !reader.isPresent())) {
+ return;
+ }
+ int remainingInFlight =
liveReader.numInFlightCheckpoints.decrementAndGet();
+ checkState(remainingInFlight >= 0, "Miscounted in-flight checkpoints");
+ reader = Optional.empty();
+ safeToDeleteIds = null;
+ }
Review Comment:
`PendingCheckpoints` holds `final SqsUnboundedReader reader` (line 188),
unlike `JmsCheckpointMark`/`AmqpCheckpointMark`. Because `clearAndDecrement()`
doesn't also set `pendingCheckpoints = null`, every finalized
`SqsCheckpointMark` still strongly retains the `SqsUnboundedReader` (defeating
`reader = Optional.empty()`) and prevents `PendingCheckpoints.LIVE` from
evicting the entry via weak values if `close()` hasn't invalidated it yet.
Setting `pendingCheckpoints = null;` here (and in the `else` branch at line
168) fixes the retention while keeping duplicate `finalizeCheckpoint()` calls a
clean no-op (via `LIVE.getIfPresent(readerId)` → empty `removeUpTo`, or
`reader` empty → line 136 return).
##########
sdks/java/io/amazon-web-services2/src/main/java/org/apache/beam/sdk/io/aws2/sqs/SqsCheckpointMark.java:
##########
@@ -68,32 +88,150 @@ class SqsCheckpointMark implements
UnboundedSource.CheckpointMark, Serializable
SqsUnboundedReader reader,
Collection<String> messagesToDelete,
Collection<String> notYetReadReceipts) {
+ this(null, 0, reader, messagesToDelete, notYetReadReceipts);
+ }
+
+ SqsCheckpointMark(
+ @Nullable PendingCheckpoints pendingCheckpoints,
+ long sequence,
+ SqsUnboundedReader reader,
+ Collection<String> messagesToDelete,
+ Collection<String> notYetReadReceipts) {
+ this.pendingCheckpoints = pendingCheckpoints;
+ this.readerId = pendingCheckpoints == null ? null :
pendingCheckpoints.readerId;
+ this.sequence = sequence;
this.reader = Optional.of(reader);
this.safeToDeleteIds = ImmutableList.copyOf(messagesToDelete);
this.notYetReadReceipts = ImmutableList.copyOf(notYetReadReceipts);
}
@Override
public void finalizeCheckpoint() throws IOException {
- checkState(
- reader.isPresent() && safeToDeleteIds != null, "Cannot finalize a
restored checkpoint");
+ PendingCheckpoints pending = pendingCheckpoints;
+ if (pending == null && readerId != null) {
+ pending = PendingCheckpoints.LIVE.getIfPresent(readerId);
+ }
+ if (pending != null) {
+ List<SqsCheckpointMark> checkpoints = pending.removeUpTo(sequence);
+ if (checkpoints.isEmpty()) {
+ return;
+ }
+ Set<String> toDelete = new LinkedHashSet<>();
+ for (SqsCheckpointMark checkpoint : checkpoints) {
+ if (checkpoint.safeToDeleteIds != null) {
+ toDelete.addAll(checkpoint.safeToDeleteIds);
+ }
+ }
+ try {
+ pending.reader.delete(new ArrayList<>(toDelete));
Review Comment:
While pre-existing in `SqsUnboundedReader.delete()`
(`SqsUnboundedReader.java:604-621`), `inFlight` is a non-thread-safe
`LinkedHashMap` mutated on the reader thread (`pull()`, `retire()`,
`extendBatch()`, and `extend()` which does `remove` + `put` at
`SqsUnboundedReader.java:834-836`) while `delete()` reads `inFlight.get(msgId)`
from finalizer/resume threads. Now that restored checkpoints and
`createReader()` actively call `delete()` on live readers, unsynchronized reads
risk `LinkedHashMap` corruption or seeing `null` during `extend()`'s remove+put
window (skipping deletion from SQS while still retiring `msgId` via
`deletedIds`).
Guarding `inFlight` accesses with a dedicated lock (collecting receipt
handles under the lock before calling `deleteBatch()`/`extendBatch()` outside
it) would make concurrent finalization genuinely thread-safe.
##########
sdks/java/io/amazon-web-services2/src/main/java/org/apache/beam/sdk/io/aws2/sqs/SqsUnboundedReader.java:
##########
@@ -520,21 +539,57 @@ public boolean advance() throws IOException {
* no in-flight checkpoints remain, the reader will be closed.
*/
@Override
+ @SuppressWarnings("FutureReturnValueIgnored")
public void close() throws IOException {
active.set(false);
- maybeCloseClient();
+ synchronized (closeLock) {
+ if (numInFlightCheckpoints.get() == 0) {
+ maybeCloseClient();
+ } else if (closeTimeoutFuture == null) {
+ ScheduledExecutorService executorService =
+ awsOptions.as(ExecutorOptions.class).getScheduledExecutorService();
+ closeTimeoutFuture =
+ executorService.schedule(
+ () -> {
+ List<SqsCheckpointMark> abandoned =
pendingCheckpoints.removeAll();
+ if (!abandoned.isEmpty()) {
+ numInFlightCheckpoints.addAndGet(-abandoned.size());
+ LOG.info(
+ "SQS reader for {} closes with {} checkpoint(s) not
finalized within {}.",
+ queueUrl(),
+ abandoned.size(),
+ DEFAULT_CLOSE_TIMEOUT);
+ }
Review Comment:
Instead of manually calling
`numInFlightCheckpoints.addAndGet(-abandoned.size())`, consider exposing a
package-private `abandon()` (or `clearAndDecrement()`) on `SqsCheckpointMark`
and invoking it on each checkpoint in `abandoned`. That clears `reader`,
`pendingCheckpoints`, and `safeToDeleteIds` on abandoned marks (avoiding memory
retention if the runner holds onto the mark) and keeps all
`numInFlightCheckpoints` decrements in one place, matching `JmsIO`/`AmqpIO`.
##########
sdks/java/io/amazon-web-services2/src/main/java/org/apache/beam/sdk/io/aws2/sqs/SqsCheckpointMark.java:
##########
@@ -68,32 +88,150 @@ class SqsCheckpointMark implements
UnboundedSource.CheckpointMark, Serializable
SqsUnboundedReader reader,
Collection<String> messagesToDelete,
Collection<String> notYetReadReceipts) {
+ this(null, 0, reader, messagesToDelete, notYetReadReceipts);
+ }
+
+ SqsCheckpointMark(
+ @Nullable PendingCheckpoints pendingCheckpoints,
+ long sequence,
+ SqsUnboundedReader reader,
+ Collection<String> messagesToDelete,
+ Collection<String> notYetReadReceipts) {
+ this.pendingCheckpoints = pendingCheckpoints;
+ this.readerId = pendingCheckpoints == null ? null :
pendingCheckpoints.readerId;
+ this.sequence = sequence;
this.reader = Optional.of(reader);
this.safeToDeleteIds = ImmutableList.copyOf(messagesToDelete);
this.notYetReadReceipts = ImmutableList.copyOf(notYetReadReceipts);
}
@Override
public void finalizeCheckpoint() throws IOException {
- checkState(
- reader.isPresent() && safeToDeleteIds != null, "Cannot finalize a
restored checkpoint");
+ PendingCheckpoints pending = pendingCheckpoints;
+ if (pending == null && readerId != null) {
+ pending = PendingCheckpoints.LIVE.getIfPresent(readerId);
+ }
+ if (pending != null) {
+ List<SqsCheckpointMark> checkpoints = pending.removeUpTo(sequence);
+ if (checkpoints.isEmpty()) {
+ return;
+ }
+ Set<String> toDelete = new LinkedHashSet<>();
+ for (SqsCheckpointMark checkpoint : checkpoints) {
+ if (checkpoint.safeToDeleteIds != null) {
+ toDelete.addAll(checkpoint.safeToDeleteIds);
+ }
+ }
+ try {
+ pending.reader.delete(new ArrayList<>(toDelete));
+ } finally {
+ for (SqsCheckpointMark checkpoint : checkpoints) {
+ checkpoint.clearAndDecrement();
+ }
+ pending.reader.maybeCloseClient();
+ }
+ return;
+ }
+
+ if (reader == null || !reader.isPresent()) {
+ LOG.debug(
+ "Finalized checkpoint {}#{}: its reader is not in this JVM, nothing
to acknowledge",
+ readerId,
+ sequence);
+ return;
+ }
+
+ checkState(safeToDeleteIds != null, "Cannot finalize an already finalized
checkpoint");
// Even if the 'true' active reader has changed since the checkpoint was
taken we are
// fine:
// - The underlying SQS topic will not have changed, so the following
deletes will still
// go to the right place.
// - We'll delete the ACK ids from the readers in-flight state, but that
only affect
// flow control and stats, neither of which are relevant anymore.
+ SqsUnboundedReader liveReader = reader.get();
try {
- reader.get().delete(safeToDeleteIds);
+ liveReader.delete(safeToDeleteIds);
} finally {
- int remainingInFlight =
reader.get().numInFlightCheckpoints.decrementAndGet();
- checkState(remainingInFlight >= 0, "Miscounted in-flight checkpoints");
- reader.get().maybeCloseClient();
+ clearAndDecrement(liveReader);
+ liveReader.maybeCloseClient();
+ }
+ }
+
+ private void clearAndDecrement() {
+ SqsUnboundedReader liveReader =
+ pendingCheckpoints != null
+ ? pendingCheckpoints.reader
+ : (reader != null && reader.isPresent() ? reader.get() : null);
+ if (liveReader != null) {
+ clearAndDecrement(liveReader);
+ } else {
reader = Optional.empty();
safeToDeleteIds = null;
}
}
+ private synchronized void clearAndDecrement(SqsUnboundedReader liveReader) {
+ if (safeToDeleteIds == null && (reader == null || !reader.isPresent())) {
+ return;
+ }
+ int remainingInFlight =
liveReader.numInFlightCheckpoints.decrementAndGet();
+ checkState(remainingInFlight >= 0, "Miscounted in-flight checkpoints");
+ reader = Optional.empty();
+ safeToDeleteIds = null;
+ }
+
+ static final class PendingCheckpoints {
+ private static final Cache<String, PendingCheckpoints> LIVE =
+ CacheBuilder.newBuilder().weakValues().build();
+
+ final String readerId = UUID.randomUUID().toString();
+ final SqsUnboundedReader reader;
+ private final List<SqsCheckpointMark> checkpoints = new ArrayList<>();
+ private long nextSequence;
+
+ private PendingCheckpoints(SqsUnboundedReader reader) {
+ this.reader = reader;
+ }
+
+ static PendingCheckpoints create(SqsUnboundedReader reader) {
+ PendingCheckpoints pending = new PendingCheckpoints(reader);
+ LIVE.put(pending.readerId, pending);
+ return pending;
+ }
+
+ synchronized long nextSequence() {
+ return nextSequence++;
+ }
+
+ synchronized void add(SqsCheckpointMark checkpoint) {
+ checkpoints.add(checkpoint);
+ }
+
+ synchronized List<SqsCheckpointMark> removeUpTo(long sequence) {
+ List<SqsCheckpointMark> removed = new ArrayList<>();
+ checkpoints.removeIf(
+ checkpoint -> {
+ if (checkpoint.sequence <= sequence) {
+ removed.add(checkpoint);
+ return true;
+ }
+ return false;
+ });
+ return removed;
+ }
+
+ synchronized List<SqsCheckpointMark> removeAll() {
+ LIVE.invalidate(readerId);
+ List<SqsCheckpointMark> removed = new ArrayList<>(checkpoints);
+ checkpoints.clear();
+ return removed;
+ }
+
+ synchronized int size() {
Review Comment:
Nit: `PendingCheckpoints.size()` is unused.
##########
sdks/java/io/amazon-web-services2/src/main/java/org/apache/beam/sdk/io/aws2/sqs/SqsUnboundedReader.java:
##########
@@ -520,21 +539,57 @@ public boolean advance() throws IOException {
* no in-flight checkpoints remain, the reader will be closed.
*/
@Override
+ @SuppressWarnings("FutureReturnValueIgnored")
Review Comment:
Nit: `@SuppressWarnings("FutureReturnValueIgnored")` is unnecessary here
since the return value of `executorService.schedule(...)` is assigned to
`closeTimeoutFuture`. Also minor: `numInFlightCheckpoints.get() == 0` on line
546 could be `<= 0` to match `maybeCloseClient()` on line 581, and
`pendingCheckpoints` creation (lines 315–316) could move to the end of the
constructor to avoid `this`-escape into `LIVE`.
--
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]