Skip to content

[RabbitMqIO] Acknowledge live and earlier checkpoints on restored finalize or resume - #41508

Open
jbonofre wants to merge 1 commit into
apache:masterfrom
jbonofre:rabbitmqio-checkpoint-registry
Open

jbonofre wants to merge 1 commit into
apache:masterfrom
jbonofre:rabbitmqio-checkpoint-registry

Conversation

@jbonofre

Copy link
Copy Markdown
Member

Similar to the recent JmsIO fixes (#40605, #41013), RabbitMQCheckpointMark previously kept transient Channel channel and transient ConcurrentLinkedQueue<Long> sessionIds, and UnboundedRabbitMqReader reused a single mutable RabbitMQCheckpointMark across all getCheckpointMark() calls:

  1. Restored checkpoints lost delivery tags and threw NPE: After serialization/deserialization via SerializableCoder, readResolve resets sessionIds to empty and leaves channel null, so finalizeCheckpoint() on a restored mark loses all pending acks and throws NullPointerException on channel.isOpen().
  2. No per-checkpoint isolation, catch-up, or deferred close: Checkpoints taken without being finalized (e.g., dropped callbacks or progress snapshots) are not caught up on subsequent finalization or on createReader(..., checkpointMark) resume, and UnboundedRabbitMqReader.close() immediately stops connectionHandler before in-flight checkpoints finalize.

Changes

  • Isolate per-checkpoint delivery tags via RabbitMQCheckpointMark.Preparer and register them in a per-reader weak-valued PendingCheckpoints registry (readerId + monotonic sequence on RabbitMQCheckpointMark, with serialVersionUID pinned for backward compatibility).
  • finalizeCheckpoint() resolves the live reader's PendingCheckpoints (even from a restored copy) and acknowledges/commits this checkpoint together with all earlier unfinalized checkpoints of the same reader in order.
  • RabbitMQSource.createReader(options, checkpointMark) finalizes the checkpoint it resumes from when its originating reader lives in this JVM.
  • UnboundedRabbitMqReader.close() waits for in-flight checkpoints to finalize (up to a 60s timeout, closing immediately once drained) before stopping connectionHandler.
  • Added unit test RabbitMqIOTest.testRestoredCheckpointAcknowledgesLiveAndEarlierCheckpoints.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📋 Review Summary

This PR updates RabbitMqIO to isolate delivery tags per checkpoint via a Preparer and a per-reader PendingCheckpoints registry, enabling restored checkpoints to acknowledge live and earlier unfinalized checkpoints and deferring connection closure until in-flight checkpoints drain. However, there are a few issues around exception handling during acknowledgment/resumption, channel lifecycle synchronization, and post-creation mutation of RabbitMQCheckpointMark.latestTimestamp.

🔍 General Feedback

  • Unlike JmsCheckpointMark.finalizeCheckpoint(), RabbitMQCheckpointMark.acknowledge() can throw IOException or com.rabbitmq.client.AlreadyClosedException (RuntimeException) without releasing activeCheckpoints or remaining checkpoints removed by removeUpTo(sequence), and can cause createReader to fail when resuming after a broken connection.
  • RabbitMQCheckpointMark shares a single transactional Channel with the reader; removeUpTo(sequence) detaches checkpoints from PendingCheckpoints before acknowledge() completes, allowing the close-timeout task to stop the connection concurrently with an in-flight acknowledge().
  • Mutating latestTimestamp on RabbitMQCheckpointMark during acknowledge() alters its serialized form after creation, which can invalidate Read.UnboundedSourceAsSDFWrapperFn reader cache keys.

💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.

// 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();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High: When a runner calls createReader(options, checkpointMark) to resume from a committed checkpoint, it is often recovering because the previous reader's connection or channel failed. Because the previous reader's close() defers abandonPendingCheckpointsAndStopConnection() for 60s while activeCheckpoints > 0, checkpointMark will still resolve the old reader in PendingCheckpoints.LIVE and attempt basicAck/txCommit on the dead channel. If that throws IOException or AlreadyClosedException (a RuntimeException), createReader will fail to create the new replacement reader instead of logging and letting the broker redeliver any unacknowledged messages (as JmsCheckpointMark does).

}

private synchronized void acknowledge() throws IOException {
Channel ch = channel;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High: In acknowledge() and finalizeCheckpoint():

  1. ch.basicAck(sessionId, false) is called without checking ch.isOpen(), and neither basicAck nor txCommit is wrapped in a try ... finally that clears sessionIds/channel and calls release(true). If basicAck or txCommit throws IOException or AlreadyClosedException, activeCheckpoints is never decremented.
  2. In finalizeCheckpoint(), pending.removeUpTo(sequence) removes all checkpoints up to sequence before iterating. If an earlier checkpoint's acknowledge() throws, the remaining checkpoints in the removed list are never acknowledged and never have release(true) called, permanently leaking their activeCheckpoints counts and preventing maybeStopConnection() from closing the connection until the 60s timeout.
  3. Because pending.removeUpTo(sequence) removes the checkpoint before acknowledge() runs, a concurrent timeout firing abandonPendingCheckpointsAndStopConnection() will not see the in-flight checkpoint in pendingCheckpoints.removeAll() and will call connectionHandler.stop() concurrently with ch.basicAck/ch.txCommit.

}
channel = null;
latestTimestamp = Instant.now();
release(true);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium: latestTimestamp is a non-transient field serialized by SerializableCoder. Read.UnboundedSourceAsSDFWrapperFn caches active readers using restrictionCoder.structuralValue(...) (which encodes the RabbitMQCheckpointMark to bytes). Mutating latestTimestamp = Instant.now() when acknowledge() runs changes the serialized bytes of an existing RabbitMQCheckpointMark instance in memory, which can cause a cache miss in cachedReaders on the next bundle if the same checkpoint instance is held in the restriction. Since getWatermark() now reads checkpointPreparer.getLatestTimestamp(), mark.latestTimestamp should not be mutated after checkpoint creation.

sessionIds.clear();
Instant checkpointTimestamp = latestTimestamp;
latestTimestamp = Instant.now();
RabbitMQCheckpointMark mark =

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Low: Unconditionally resetting latestTimestamp = Instant.now() in newCheckpoint() can cause getWatermark() to move backwards if a message had a timestamp slightly ahead of Instant.now() (e.g., due to producer clock skew). Using advanceWatermark(Instant.now()) preserves monotonicity.

Suggested change
RabbitMQCheckpointMark mark =
advanceWatermark(Instant.now());

@github-actions github-actions Bot added java io rabbitmq size/m M: 50-249 lines changed labels Nov 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @damccorm for label java.
Backup reviewer: kennknowles (if the main reviewer is unresponsive, you can escalate to them by tagging their username)

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +482 to +510
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);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

sessionIds.clear();
}
channel = null;
latestTimestamp = Instant.now();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

ConcurrentLinkedQueue<Long> snapshot = new ConcurrentLinkedQueue<>(sessionIds);
sessionIds.clear();
Instant checkpointTimestamp = latestTimestamp;
latestTimestamp = Instant.now();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: advanceWatermark(Instant.now()) here would keep getWatermark() monotonic in case a message timestamp was slightly ahead of local wall clock time.

Comment on lines +800 to +805
ScheduledExecutorService executorService =
options.as(ExecutorOptions.class).getScheduledExecutorService();
executorService.schedule(
this::abandonPendingCheckpointsAndStopConnection,
DEFAULT_CLOSE_TIMEOUT.getMillis(),
TimeUnit.MILLISECONDS);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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").

cp1.finalizeCheckpoint();

// All 3 messages were acknowledged, so none remain or are redelivered in the queue.
assertNull(channel.basicGet(queue, true));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants