Repository navigation
Conversation
There was a problem hiding this comment.
📋 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 throwIOExceptionorcom.rabbitmq.client.AlreadyClosedException(RuntimeException) without releasingactiveCheckpointsor remaining checkpoints removed byremoveUpTo(sequence), and can causecreateReaderto fail when resuming after a broken connection. RabbitMQCheckpointMarkshares a single transactionalChannelwith the reader;removeUpTo(sequence)detaches checkpoints fromPendingCheckpointsbeforeacknowledge()completes, allowing the close-timeout task to stop the connection concurrently with an in-flightacknowledge().- Mutating
latestTimestamponRabbitMQCheckpointMarkduringacknowledge()alters its serialized form after creation, which can invalidateRead.UnboundedSourceAsSDFWrapperFnreader 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(); | ||
| } |
There was a problem hiding this comment.
🟠 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; |
There was a problem hiding this comment.
🟠 High: In acknowledge() and finalizeCheckpoint():
ch.basicAck(sessionId, false)is called without checkingch.isOpen(), and neitherbasicAcknortxCommitis wrapped in atry ... finallythat clearssessionIds/channeland callsrelease(true). IfbasicAckortxCommitthrowsIOExceptionorAlreadyClosedException,activeCheckpointsis never decremented.- In
finalizeCheckpoint(),pending.removeUpTo(sequence)removes all checkpoints up tosequencebefore iterating. If an earlier checkpoint'sacknowledge()throws, the remaining checkpoints in the removed list are never acknowledged and never haverelease(true)called, permanently leaking theiractiveCheckpointscounts and preventingmaybeStopConnection()from closing the connection until the 60s timeout. - Because
pending.removeUpTo(sequence)removes the checkpoint beforeacknowledge()runs, a concurrent timeout firingabandonPendingCheckpointsAndStopConnection()will not see the in-flight checkpoint inpendingCheckpoints.removeAll()and will callconnectionHandler.stop()concurrently withch.basicAck/ch.txCommit.
| } | ||
| channel = null; | ||
| latestTimestamp = Instant.now(); | ||
| release(true); |
There was a problem hiding this comment.
🟡 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 = |
There was a problem hiding this comment.
🟢 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.
| RabbitMQCheckpointMark mark = | |
| advanceWatermark(Instant.now()); |
|
Assigning reviewers: R: @damccorm for label java. 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). |
| 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(); |
There was a problem hiding this 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.
| 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); | ||
| } |
There was a problem hiding this comment.
A couple of concerns around error handling and concurrency here:
- If
ch.basicAckorch.txCommitthrows (IOExceptionor RabbitMQ'sAlreadyClosedException),acknowledge()exits without clearingsessionIds/channelor callingrelease(true), soactiveCheckpointsnever decrements. On top of that,pending.removeUpTo(sequence)already detached all the checkpoints up tosequence, so an exception on an earlier one aborts the loop and leaves the rest orphaned with theiractiveCheckpointscounts leaked until the 60s timeout. Checkingch.isOpen()beforebasicAck, cleaning up and callingrelease(true)in afinallyblock, and making sure we still release every removed checkpoint in the loop would avoid that (similar to howJmsCheckpointMarktreats ack failures as non-fatal). - Since
acknowledge()only synchronizes on the individual checkpoint mark, we don't have mutual exclusion on the shared transactionalChannel: two concurrentfinalizeCheckpoint()calls can interleavebasicAck/txCommit,acknowledge()can run alongsideadvance()'sbasicGet, and the 60s timeout can callconnectionHandler.stop()while an already-detached checkpoint is mid-ack. Sharing a per-reader lock acrossbasicGet,basicAck+txCommit, andconnectionHandler.stop()would close those races.
| sessionIds.clear(); | ||
| } | ||
| channel = null; | ||
| latestTimestamp = Instant.now(); |
There was a problem hiding this 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.
| ConcurrentLinkedQueue<Long> snapshot = new ConcurrentLinkedQueue<>(sessionIds); | ||
| sessionIds.clear(); | ||
| Instant checkpointTimestamp = latestTimestamp; | ||
| latestTimestamp = Instant.now(); |
There was a problem hiding this comment.
Minor: advanceWatermark(Instant.now()) here would keep getWatermark() monotonic in case a message timestamp was slightly ahead of local wall clock time.
| ScheduledExecutorService executorService = | ||
| options.as(ExecutorOptions.class).getScheduledExecutorService(); | ||
| executorService.schedule( | ||
| this::abandonPendingCheckpointsAndStopConnection, | ||
| DEFAULT_CLOSE_TIMEOUT.getMillis(), | ||
| TimeUnit.MILLISECONDS); |
There was a problem hiding this 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").
| cp1.finalizeCheckpoint(); | ||
|
|
||
| // All 3 messages were acknowledged, so none remain or are redelivered in the queue. | ||
| assertNull(channel.basicGet(queue, true)); |
There was a problem hiding this 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)?
Similar to the recent JmsIO fixes (#40605, #41013),
RabbitMQCheckpointMarkpreviously kepttransient Channel channelandtransient ConcurrentLinkedQueue<Long> sessionIds, andUnboundedRabbitMqReaderreused a single mutableRabbitMQCheckpointMarkacross allgetCheckpointMark()calls:SerializableCoder,readResolveresetssessionIdsto empty and leaveschannelnull, sofinalizeCheckpoint()on a restored mark loses all pending acks and throwsNullPointerExceptiononchannel.isOpen().createReader(..., checkpointMark)resume, andUnboundedRabbitMqReader.close()immediately stopsconnectionHandlerbefore in-flight checkpoints finalize.Changes
RabbitMQCheckpointMark.Preparerand register them in a per-reader weak-valuedPendingCheckpointsregistry (readerId+ monotonicsequenceonRabbitMQCheckpointMark, withserialVersionUIDpinned for backward compatibility).finalizeCheckpoint()resolves the live reader'sPendingCheckpoints(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 stoppingconnectionHandler.RabbitMqIOTest.testRestoredCheckpointAcknowledgesLiveAndEarlierCheckpoints.