damccorm commented on code in PR #41508:
URL: https://github.com/apache/beam/pull/41508#discussion_r4673052919
##########
sdks/java/io/rabbitmq/src/main/java/org/apache/beam/sdk/io/rabbitmq/RabbitMqIO.java:
##########
@@ -395,8 +406,14 @@ public List<RabbitMQSource> split(int desiredNumSplits,
PipelineOptions options)
@Override
public UnboundedReader<RabbitMqMessage> createReader(
- PipelineOptions options, RabbitMQCheckpointMark checkpointMark) throws
IOException {
- return new UnboundedRabbitMqReader(this, checkpointMark);
+ PipelineOptions options, @Nullable RabbitMQCheckpointMark
checkpointMark)
+ throws IOException {
+ if (checkpointMark != null) {
+ // A runner resumes from a checkpoint only once it is committed, so
its messages can be
+ // acknowledged if the reader that took it lives in this JVM.
+ checkpointMark.finalizeCheckpoint();
Review Comment:
Should we catch and log exceptions here? If the runner is calling
`createReader` to recover after the old reader's connection broke, the old
reader may still be in `PendingCheckpoints.LIVE` waiting on the 60s close
timeout. If finalizing on that dead channel throws `IOException` or
`AlreadyClosedException`, we'll block creating the replacement reader instead
of letting it reconnect and having RabbitMQ redeliver anything unacked.
##########
sdks/java/io/rabbitmq/src/main/java/org/apache/beam/sdk/io/rabbitmq/RabbitMqIO.java:
##########
@@ -410,71 +427,256 @@ public boolean requiresDeduping() {
}
}
- private static class RabbitMQCheckpointMark
- implements UnboundedSource.CheckpointMark, Serializable {
- transient Channel channel;
+ @VisibleForTesting
+ static class RabbitMQCheckpointMark implements
UnboundedSource.CheckpointMark, Serializable {
+
+ // Pinned to the value computed before readerId and sequence were added,
so checkpoints written
+ // by older versions can still be decoded.
+ private static final long serialVersionUID = -961062677995876719L;
+
+ private final @Nullable String readerId;
+ private final long sequence;
+ transient @Nullable Channel channel;
Instant latestTimestamp = Instant.now();
transient ConcurrentLinkedQueue<Long> sessionIds = new
ConcurrentLinkedQueue<>();
+ transient @Nullable PendingCheckpoints pendingCheckpoints;
+ transient @Nullable AtomicInteger activeCheckpoints;
+ transient @Nullable Runnable onCheckpointFinalized;
+
+ RabbitMQCheckpointMark() {
+ this(null, 0, null, Instant.now(), new ConcurrentLinkedQueue<>(), null,
null);
+ }
+
+ private RabbitMQCheckpointMark(
+ @Nullable PendingCheckpoints pendingCheckpoints,
+ long sequence,
+ @Nullable Channel channel,
+ Instant latestTimestamp,
+ ConcurrentLinkedQueue<Long> sessionIds,
+ @Nullable AtomicInteger activeCheckpoints,
+ @Nullable Runnable onCheckpointFinalized) {
+ this.pendingCheckpoints = pendingCheckpoints;
+ this.readerId = pendingCheckpoints == null ? null :
pendingCheckpoints.readerId;
+ this.sequence = sequence;
+ this.channel = channel;
+ this.latestTimestamp = latestTimestamp;
+ this.sessionIds = sessionIds;
+ this.activeCheckpoints = activeCheckpoints;
+ this.onCheckpointFinalized = onCheckpointFinalized;
+ }
// this method is called after deserialization on the deserialized object
- private Object readResolve() {
+ private synchronized Object readResolve() {
// (re-)initialize transient fields as required
this.sessionIds = new ConcurrentLinkedQueue<>();
return this;
}
- /**
- * Advances the watermark to the provided time, provided said time is
after the current
- * watermark. If the provided time is before the latest, this function
no-ops.
- *
- * @param time The time to advance the watermark to
- */
- public void advanceWatermark(Instant time) {
- if (time.isAfter(latestTimestamp)) {
- latestTimestamp = time;
- }
- }
-
@Override
public void finalizeCheckpoint() throws IOException {
- Long sessionId = sessionIds.poll();
- while (sessionId != null) {
- channel.basicAck(sessionId, false);
- sessionId = sessionIds.poll();
+ PendingCheckpoints pending = pendingCheckpoints;
+ if (pending == null && readerId != null) {
+ pending = PendingCheckpoints.LIVE.getIfPresent(readerId);
+ }
+ if (pending != null) {
+ for (RabbitMQCheckpointMark checkpoint : pending.removeUpTo(sequence))
{
+ checkpoint.acknowledge();
+ }
+ return;
}
- if (channel.isOpen()) {
- channel.txCommit();
+ if (readerId != null) {
+ return;
+ }
+ acknowledge();
+ }
+
+ private synchronized void acknowledge() throws IOException {
+ Channel ch = channel;
+ if (ch != null) {
+ Long sessionId = sessionIds.poll();
+ while (sessionId != null) {
+ ch.basicAck(sessionId, false);
+ sessionId = sessionIds.poll();
+ }
+ if (ch.isOpen()) {
+ ch.txCommit();
+ }
+ } else {
+ sessionIds.clear();
}
+ channel = null;
latestTimestamp = Instant.now();
+ release(true);
+ }
Review Comment:
A couple of concerns around error handling and concurrency here:
1. If `ch.basicAck` or `ch.txCommit` throws (`IOException` or RabbitMQ's
`AlreadyClosedException`), `acknowledge()` exits without clearing
`sessionIds`/`channel` or calling `release(true)`, so `activeCheckpoints` never
decrements. On top of that, `pending.removeUpTo(sequence)` already detached all
the checkpoints up to `sequence`, so an exception on an earlier one aborts the
loop and leaves the rest orphaned with their `activeCheckpoints` counts leaked
until the 60s timeout. Checking `ch.isOpen()` before `basicAck`, cleaning up
and calling `release(true)` in a `finally` block, and making sure we still
release every removed checkpoint in the loop would avoid that (similar to how
`JmsCheckpointMark` treats ack failures as non-fatal).
2. Since `acknowledge()` only synchronizes on the individual checkpoint
mark, we don't have mutual exclusion on the shared transactional `Channel`: two
concurrent `finalizeCheckpoint()` calls can interleave `basicAck`/`txCommit`,
`acknowledge()` can run alongside `advance()`'s `basicGet`, and the 60s timeout
can call `connectionHandler.stop()` while an already-detached checkpoint is
mid-ack. Sharing a per-reader lock across `basicGet`, `basicAck`+`txCommit`,
and `connectionHandler.stop()` would close those races.
##########
sdks/java/io/rabbitmq/src/main/java/org/apache/beam/sdk/io/rabbitmq/RabbitMqIO.java:
##########
@@ -410,71 +427,256 @@ public boolean requiresDeduping() {
}
}
- private static class RabbitMQCheckpointMark
- implements UnboundedSource.CheckpointMark, Serializable {
- transient Channel channel;
+ @VisibleForTesting
+ static class RabbitMQCheckpointMark implements
UnboundedSource.CheckpointMark, Serializable {
+
+ // Pinned to the value computed before readerId and sequence were added,
so checkpoints written
+ // by older versions can still be decoded.
+ private static final long serialVersionUID = -961062677995876719L;
+
+ private final @Nullable String readerId;
+ private final long sequence;
+ transient @Nullable Channel channel;
Instant latestTimestamp = Instant.now();
transient ConcurrentLinkedQueue<Long> sessionIds = new
ConcurrentLinkedQueue<>();
+ transient @Nullable PendingCheckpoints pendingCheckpoints;
+ transient @Nullable AtomicInteger activeCheckpoints;
+ transient @Nullable Runnable onCheckpointFinalized;
+
+ RabbitMQCheckpointMark() {
+ this(null, 0, null, Instant.now(), new ConcurrentLinkedQueue<>(), null,
null);
+ }
+
+ private RabbitMQCheckpointMark(
+ @Nullable PendingCheckpoints pendingCheckpoints,
+ long sequence,
+ @Nullable Channel channel,
+ Instant latestTimestamp,
+ ConcurrentLinkedQueue<Long> sessionIds,
+ @Nullable AtomicInteger activeCheckpoints,
+ @Nullable Runnable onCheckpointFinalized) {
+ this.pendingCheckpoints = pendingCheckpoints;
+ this.readerId = pendingCheckpoints == null ? null :
pendingCheckpoints.readerId;
+ this.sequence = sequence;
+ this.channel = channel;
+ this.latestTimestamp = latestTimestamp;
+ this.sessionIds = sessionIds;
+ this.activeCheckpoints = activeCheckpoints;
+ this.onCheckpointFinalized = onCheckpointFinalized;
+ }
// this method is called after deserialization on the deserialized object
- private Object readResolve() {
+ private synchronized Object readResolve() {
// (re-)initialize transient fields as required
this.sessionIds = new ConcurrentLinkedQueue<>();
return this;
}
- /**
- * Advances the watermark to the provided time, provided said time is
after the current
- * watermark. If the provided time is before the latest, this function
no-ops.
- *
- * @param time The time to advance the watermark to
- */
- public void advanceWatermark(Instant time) {
- if (time.isAfter(latestTimestamp)) {
- latestTimestamp = time;
- }
- }
-
@Override
public void finalizeCheckpoint() throws IOException {
- Long sessionId = sessionIds.poll();
- while (sessionId != null) {
- channel.basicAck(sessionId, false);
- sessionId = sessionIds.poll();
+ PendingCheckpoints pending = pendingCheckpoints;
+ if (pending == null && readerId != null) {
+ pending = PendingCheckpoints.LIVE.getIfPresent(readerId);
+ }
+ if (pending != null) {
+ for (RabbitMQCheckpointMark checkpoint : pending.removeUpTo(sequence))
{
+ checkpoint.acknowledge();
+ }
+ return;
}
- if (channel.isOpen()) {
- channel.txCommit();
+ if (readerId != null) {
+ return;
+ }
+ acknowledge();
+ }
+
+ private synchronized void acknowledge() throws IOException {
+ Channel ch = channel;
+ if (ch != null) {
+ Long sessionId = sessionIds.poll();
+ while (sessionId != null) {
+ ch.basicAck(sessionId, false);
+ sessionId = sessionIds.poll();
+ }
+ if (ch.isOpen()) {
+ ch.txCommit();
+ }
+ } else {
+ sessionIds.clear();
}
+ channel = null;
latestTimestamp = Instant.now();
Review Comment:
We should drop this line (and can make `latestTimestamp` `final`). Since
`latestTimestamp` is serialized by `SerializableCoder` and
`Read.UnboundedSourceAsSDFWrapperFn` keys `cachedReaders` on
`restrictionCoder.structuralValue(...)`, mutating it here changes the mark's
serialized form in memory and can cause reader cache misses. Nothing reads
`mark.latestTimestamp` after `acknowledge()` anyway now that `getWatermark()`
uses `checkpointPreparer`.
##########
sdks/java/io/rabbitmq/src/main/java/org/apache/beam/sdk/io/rabbitmq/RabbitMqIO.java:
##########
@@ -582,9 +790,41 @@ public boolean advance() throws IOException {
}
@Override
+ @SuppressWarnings("FutureReturnValueIgnored")
public void close() throws IOException {
- if (connectionHandler != null) {
- connectionHandler.stop();
+ closed.set(true);
+ checkpointPreparer.discard();
+ if (activeCheckpoints.get() == 0) {
+ abandonPendingCheckpointsAndStopConnection();
+ } else {
+ ScheduledExecutorService executorService =
+ options.as(ExecutorOptions.class).getScheduledExecutorService();
+ executorService.schedule(
+ this::abandonPendingCheckpointsAndStopConnection,
+ DEFAULT_CLOSE_TIMEOUT.getMillis(),
+ TimeUnit.MILLISECONDS);
Review Comment:
Could we save this `ScheduledFuture` (under `closeLock`) and cancel it
inside `abandonPendingCheckpointsAndStopConnection()`? Otherwise every closed
reader with an in-flight checkpoint stays retained in the shared executor queue
for 60s even if its checkpoints drain right away, and cancelling it also lets
us drop the `@SuppressWarnings("FutureReturnValueIgnored")`.
##########
sdks/java/io/rabbitmq/src/test/java/org/apache/beam/sdk/io/rabbitmq/RabbitMqIOTest.java:
##########
@@ -478,4 +482,62 @@ public void testWriteExchange() throws Exception {
}
}
}
+
+ @Test
+ public void testRestoredCheckpointAcknowledgesLiveAndEarlierCheckpoints()
throws Exception {
+ String queue = "RESTORE_CP_QUEUE_" + UUID.randomUUID();
+ String uri = "amqp://guest:guest@localhost:" + port;
+
+ ConnectionFactory connectionFactory = new ConnectionFactory();
+ connectionFactory.setUri(uri);
+ try (Connection connection = connectionFactory.newConnection();
+ Channel channel = connection.createChannel()) {
+ channel.queueDeclare(queue, false, false, false, null);
+ for (int i = 0; i < 3; i++) {
+ channel.basicPublish("", queue, null, ("msg-" +
i).getBytes(StandardCharsets.UTF_8));
+ }
+
+ RabbitMqIO.RabbitMQSource source =
+ new
RabbitMqIO.RabbitMQSource(RabbitMqIO.read().withUri(uri).withQueue(queue));
+ UnboundedSource.UnboundedReader<RabbitMqMessage> reader =
+ source.createReader(PipelineOptionsFactory.create(), null);
+
+ assertTrue(reader.start());
+ // Take cp1 (msg-0) and leave it unfinalized.
+ RabbitMqIO.RabbitMQCheckpointMark cp1 =
+ (RabbitMqIO.RabbitMQCheckpointMark) reader.getCheckpointMark();
+
+ assertTrue(reader.advance());
+ // Take cp2 (msg-1) and an empty checkpoint right after cp2.
+ RabbitMqIO.RabbitMQCheckpointMark cp2 =
+ (RabbitMqIO.RabbitMQCheckpointMark) reader.getCheckpointMark();
+ RabbitMqIO.RabbitMQCheckpointMark emptyCp =
+ (RabbitMqIO.RabbitMQCheckpointMark) reader.getCheckpointMark();
+
+ assertTrue(reader.advance());
+ // Take cp3 (msg-2), then close the reader before finalizing restored
cp2 and resuming cp3.
+ RabbitMqIO.RabbitMQCheckpointMark cp3 =
+ (RabbitMqIO.RabbitMQCheckpointMark) reader.getCheckpointMark();
+ reader.close();
+
+ // Restored cp2 acknowledges both cp1 and cp2 even after reader.close().
+ RabbitMqIO.RabbitMQCheckpointMark restoredCp2 =
+ CoderUtils.clone(source.getCheckpointMarkCoder(), cp2);
+ restoredCp2.finalizeCheckpoint();
+ emptyCp.finalizeCheckpoint();
+
+ // Resuming from restored cp3 acknowledges cp3 on the still-open
channel, then closes it.
+ RabbitMqIO.RabbitMQCheckpointMark restoredCp3 =
+ CoderUtils.clone(source.getCheckpointMarkCoder(), cp3);
+ UnboundedSource.UnboundedReader<RabbitMqMessage> resumed =
+ source.createReader(PipelineOptionsFactory.create(), restoredCp3);
+ resumed.close();
+
+ // Calling finalize on already-acknowledged cp1 is a no-op.
+ cp1.finalizeCheckpoint();
+
+ // All 3 messages were acknowledged, so none remain or are redelivered
in the queue.
+ assertNull(channel.basicGet(queue, true));
Review Comment:
Once the closed-channel error handling is updated, could we also add a test
covering finalizing/resuming when the old reader's channel is already closed
(verifying `createReader` still succeeds and `activeCheckpoints` drains)?
##########
sdks/java/io/rabbitmq/src/main/java/org/apache/beam/sdk/io/rabbitmq/RabbitMqIO.java:
##########
@@ -410,71 +427,256 @@ public boolean requiresDeduping() {
}
}
- private static class RabbitMQCheckpointMark
- implements UnboundedSource.CheckpointMark, Serializable {
- transient Channel channel;
+ @VisibleForTesting
+ static class RabbitMQCheckpointMark implements
UnboundedSource.CheckpointMark, Serializable {
+
+ // Pinned to the value computed before readerId and sequence were added,
so checkpoints written
+ // by older versions can still be decoded.
+ private static final long serialVersionUID = -961062677995876719L;
+
+ private final @Nullable String readerId;
+ private final long sequence;
+ transient @Nullable Channel channel;
Instant latestTimestamp = Instant.now();
transient ConcurrentLinkedQueue<Long> sessionIds = new
ConcurrentLinkedQueue<>();
+ transient @Nullable PendingCheckpoints pendingCheckpoints;
+ transient @Nullable AtomicInteger activeCheckpoints;
+ transient @Nullable Runnable onCheckpointFinalized;
+
+ RabbitMQCheckpointMark() {
+ this(null, 0, null, Instant.now(), new ConcurrentLinkedQueue<>(), null,
null);
+ }
+
+ private RabbitMQCheckpointMark(
+ @Nullable PendingCheckpoints pendingCheckpoints,
+ long sequence,
+ @Nullable Channel channel,
+ Instant latestTimestamp,
+ ConcurrentLinkedQueue<Long> sessionIds,
+ @Nullable AtomicInteger activeCheckpoints,
+ @Nullable Runnable onCheckpointFinalized) {
+ this.pendingCheckpoints = pendingCheckpoints;
+ this.readerId = pendingCheckpoints == null ? null :
pendingCheckpoints.readerId;
+ this.sequence = sequence;
+ this.channel = channel;
+ this.latestTimestamp = latestTimestamp;
+ this.sessionIds = sessionIds;
+ this.activeCheckpoints = activeCheckpoints;
+ this.onCheckpointFinalized = onCheckpointFinalized;
+ }
// this method is called after deserialization on the deserialized object
- private Object readResolve() {
+ private synchronized Object readResolve() {
// (re-)initialize transient fields as required
this.sessionIds = new ConcurrentLinkedQueue<>();
return this;
}
- /**
- * Advances the watermark to the provided time, provided said time is
after the current
- * watermark. If the provided time is before the latest, this function
no-ops.
- *
- * @param time The time to advance the watermark to
- */
- public void advanceWatermark(Instant time) {
- if (time.isAfter(latestTimestamp)) {
- latestTimestamp = time;
- }
- }
-
@Override
public void finalizeCheckpoint() throws IOException {
- Long sessionId = sessionIds.poll();
- while (sessionId != null) {
- channel.basicAck(sessionId, false);
- sessionId = sessionIds.poll();
+ PendingCheckpoints pending = pendingCheckpoints;
+ if (pending == null && readerId != null) {
+ pending = PendingCheckpoints.LIVE.getIfPresent(readerId);
+ }
+ if (pending != null) {
+ for (RabbitMQCheckpointMark checkpoint : pending.removeUpTo(sequence))
{
+ checkpoint.acknowledge();
+ }
+ return;
}
- if (channel.isOpen()) {
- channel.txCommit();
+ if (readerId != null) {
+ return;
+ }
+ acknowledge();
+ }
+
+ private synchronized void acknowledge() throws IOException {
+ Channel ch = channel;
+ if (ch != null) {
+ Long sessionId = sessionIds.poll();
+ while (sessionId != null) {
+ ch.basicAck(sessionId, false);
+ sessionId = sessionIds.poll();
+ }
+ if (ch.isOpen()) {
+ ch.txCommit();
+ }
+ } else {
+ sessionIds.clear();
}
+ channel = null;
latestTimestamp = Instant.now();
+ release(true);
+ }
+
+ private synchronized void abandon() {
+ sessionIds.clear();
+ channel = null;
+ release(false);
+ }
+
+ private void release(boolean notifyIfDrained) {
+ if (activeCheckpoints != null) {
+ int remaining = activeCheckpoints.decrementAndGet();
+ activeCheckpoints = null;
+ if (notifyIfDrained && remaining == 0 && onCheckpointFinalized !=
null) {
+ onCheckpointFinalized.run();
+ }
+ }
+ }
+
+ private static final class PendingCheckpoints {
+ private static final Cache<String, PendingCheckpoints> LIVE =
+ CacheBuilder.newBuilder().weakValues().build();
+
+ private final String readerId = UUID.randomUUID().toString();
+ private final List<RabbitMQCheckpointMark> checkpoints = new
ArrayList<>();
+ private long nextSequence;
+
+ static PendingCheckpoints create() {
+ PendingCheckpoints pending = new PendingCheckpoints();
+ LIVE.put(pending.readerId, pending);
+ return pending;
+ }
+
+ synchronized long nextSequence() {
+ return nextSequence++;
+ }
+
+ synchronized void add(RabbitMQCheckpointMark checkpoint) {
+ checkpoints.add(checkpoint);
+ }
+
+ synchronized List<RabbitMQCheckpointMark> removeUpTo(long sequence) {
+ List<RabbitMQCheckpointMark> removed = new ArrayList<>();
+ checkpoints.removeIf(
+ checkpoint -> {
+ if (checkpoint.sequence <= sequence) {
+ removed.add(checkpoint);
+ return true;
+ }
+ return false;
+ });
+ return removed;
+ }
+
+ synchronized List<RabbitMQCheckpointMark> removeAll() {
+ LIVE.invalidate(readerId);
+ List<RabbitMQCheckpointMark> removed = new ArrayList<>(checkpoints);
+ checkpoints.clear();
+ return removed;
+ }
+ }
+
+ static class Preparer {
+ private final PendingCheckpoints pendingCheckpoints =
PendingCheckpoints.create();
+ private final List<Long> sessionIds = new ArrayList<>();
+ private volatile Instant latestTimestamp = Instant.now();
+ private boolean discarded = false;
+
+ synchronized void add(long deliveryTag) {
+ if (discarded) {
+ throw new IllegalStateException("Attempting to add delivery tag to
discarded checkpoint");
+ }
+ sessionIds.add(deliveryTag);
+ }
+
+ /**
+ * Advances the watermark to the provided time, provided said time is
after the current
+ * watermark. If the provided time is before the latest, this function
no-ops.
+ */
+ synchronized void advanceWatermark(Instant time) {
+ if (time.isAfter(latestTimestamp)) {
+ latestTimestamp = time;
+ }
+ }
+
+ Instant getLatestTimestamp() {
+ return latestTimestamp;
+ }
+
+ synchronized void discard() {
+ sessionIds.clear();
+ discarded = true;
+ }
+
+ synchronized RabbitMQCheckpointMark newCheckpoint(
+ @Nullable Channel channel,
+ @Nullable AtomicInteger activeCheckpoints,
+ @Nullable Runnable onCheckpointFinalized) {
+ if (discarded || sessionIds.isEmpty()) {
+ sessionIds.clear();
+ return new RabbitMQCheckpointMark(
+ pendingCheckpoints,
+ pendingCheckpoints.nextSequence(),
+ null,
+ latestTimestamp,
+ new ConcurrentLinkedQueue<>(),
+ null,
+ null);
+ }
+ ConcurrentLinkedQueue<Long> snapshot = new
ConcurrentLinkedQueue<>(sessionIds);
+ sessionIds.clear();
+ Instant checkpointTimestamp = latestTimestamp;
+ latestTimestamp = Instant.now();
Review Comment:
Minor: `advanceWatermark(Instant.now())` here would keep `getWatermark()`
monotonic in case a message timestamp was slightly ahead of local wall clock
time.
--
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]